current position:Home>How can C language use a function to find characters and replace them

How can C language use a function to find characters and replace them

2022-02-02 22:49:37 CSDN Q & A

img


I don't know how to find characters in a string , What should I do with a pointer .
This should not be as troublesome as string replacement




Refer to the answer 1:
#include <stdio.h>char *strchange(char * str, char c1,char c2);void main() {    printf(" Input string :");    char str[255];    scanf("%s", str);    char c1, c2;    printf(" Enter the character you want to replace :");       getchar();    scanf("%c",&c1);     printf(" The input is replaced with characters :");    getchar();    c2 = getchar();    char *s = strchange(str, c1, c2);    printf("%s", s);    free(s);    scanf("%s", str); }char *strchange(char * str, char c1, char c2) {    int len=0;    for (; str[len]; len++);    if (len == 0)    {       char *s = (char*)malloc(sizeof(char));       s[0]=0;        return s;      }    char *s = (char*)malloc(sizeof(char)*(len + 1));    for (int i = 0; i < len; i++)    {        if (str[i] == c1)            s[i] = c2;        else        {            s[i]=str[i];        }    }    s[len] = 0;    return s;}

Running results :

img




Refer to the answer 2:



Refer to the answer 3:



Refer to the answer 4:

copyright notice
author[CSDN Q & A],Please bring the original link to reprint, thank you.
https://en.primo.wiki/2022/02/202202022249341074.html

Random recommended