Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard function to replace character or substring in a char array? [duplicate]

Tags:

c

string

replace

I need a function from the standard library that replaces all occurrences of a character in a string by another character.

I also need a function from the standard library that replaces all occurrences of a substring in a string by another string.

Are there any such functions in the standard library?

like image 213
MOHAMED Avatar asked Sep 10 '15 08:09

MOHAMED


People also ask

How do I replace a character in a character array?

Using toCharArray() method The idea is to convert the given string to a character array using its toCharArray() method and then replace the character at the given index in the character array. Finally, convert the character array back into a string using String. valueOf(char[]) method.

Which string function can be used to replace a substring?

By default, . replace() will replace all instances of the substring. However, you can use count to specify the number of occurrences you want to be replaced.

Which function is used to replace a sequence of characters with another set of characters?

Syntax. The REPLACE and REPLACEB function syntax has the following arguments: Old_text Required. Text in which you want to replace some characters.

How do you replace a substring in a string?

Algorithm to Replace a substring in a stringInput the full string (s1). Input the substring from the full string (s2). Input the string to be replaced with the substring (s3). Find the substring from the full string and replace the new substring with the old substring (Find s2 from s1 and replace s1 by s3).


1 Answers

There is no direct function to do that. You have to write something like this, using strchr:

char* replace_char(char* str, char find, char replace){
    char *current_pos = strchr(str,find);
    while (current_pos) {
        *current_pos = replace;
        current_pos = strchr(current_pos,find);
    }
    return str;
}

For whole strings, I refer to this answered question

like image 134
Superlokkus Avatar answered Oct 10 '22 16:10

Superlokkus