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ế.
Code:
/***************Replace character in string****************/
#include <conio.h>
#include <stdio.h>
void replStr(char* s, char c, char newc);
void main()
{
char s[] = "ngoton 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ả:
1 |
Space is replaced by '_', new string = ngoton_blog_for_every_one |
Leave a Reply