Hi, I am

Ngô Tôn

I am a programmer.

Home / Programming / C/C++ / Thay thế kí tự bất kì trong chuỗi bằng kí tự mới

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ế.
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ả:

About ngoton

Ngô Tôn is a programmer with passion for tailored software solutions. Comes with 7+ years of IT experience, to execute beautiful front-end experiences with secure and robust back-end solutions.

Check Also

Xây dựng hàm bạn để tính diện tích hình chữ nhật

Yêu cầu: Xây dựng hàm bạn để tính diện tích hình chữ nhật Code: Giải …

Leave a Reply

avatar
  Subscribe  
Notify of