Thay thế kí tự bất kì trong chuỗi bằng kí tự mới

Yêu cầu:

  • Viết hàm replace kí tự c trong chuỗi bằng kí tự mới newc

Giải thuật:

  • Duyệt mảng kí tự, so sánh kí tự của mảng khí tự với kí tự cần thay thế.
/***************Replace character in string****************
* When          Who         What
* 03/05/2016    vncoding    create
***********************************************************/
#include <conio.h>
#include <stdio.h>

void replStr(char* s, char c, char newc);

void main()
{
    char s[] = "vncoding blog for every one";
    replStr(s, ' ', '_');
    printf("Space is replaced by \'_\', new string = %s", s);
    getch();
}


/*********************************************
Function : replStr()
Parameter: [IN][OUT] s: string
           [IN] c: characeter
           [IN] newc: character
Return   : void
**********************************************/
void replStr(char* s, char c, char newc)
{
    int idx, cnt = 0;
    for (idx = 0; s[idx] != NULL; idx++)
    {
        if (s[idx] == c)
        {
            s[idx] = newc;
        }
    }
}

Kết quả:

Thay thế kí tự bằng kí tự mới
Thay thế kí tự bằng kí tự mới

Be the first to comment

Leave a Reply