1

I am writing a program that replaces characters in the user's input in C but I don't know how to replace the certain characters. Is there a certain method for C that replaces characters in a string? If you know python, then I want something a bit like this in python:

string.replace('certain_character','replacement_character')

Something like that, except for C, and not python. This is my code that I have written so far:

#include <stdio.h>

int main(){
char str[BUFSIZ];

printf("Welcome To My Secret Language encoder!Enter some text: \n");
scanf("%s",str);

/* 
    Where I want to replace certain characters
*/

printf("Here is your text in secret language mode: %s \n",str);

}

I'm writing this code to learn C more, and that's why i'm not doing it in a higher level language like python.So, how do you replace certain characters in a string?

Darryl Tanzil
  • 335
  • 1
  • 3
  • 10
  • `BUFSIZ` refers to the I/O buffer size used by stdio. It is implementation-dependent and not always accurate. You should specify your own buffer size, or better, use a loop. – Potatoswatter Dec 15 '13 at 04:13
  • If you're willing to use STL (if you're learning C++, it's highly recommended you do so) see this similar question in StackOverflow: http://stackoverflow.com/questions/2896600/how-to-replace-all-occurrences-of-a-character-in-string – Moshe Rubin Dec 15 '13 at 04:20

5 Answers5

0

Nothing like that in C. You'll have to scan the string yourself:

#include <string.h>

char str[] = "I love cats";
int i;

for(i = 0; i < strlen(str); i++)
{
    if(str[i] == 'c')
        str[i] = 'b';
}

Now, if you're looking for a substring, you'll need something like strstr.

Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46
0

strchr finds the given character in a string, or returns NULL.

int main() {
    int c;
    while ( ( c = getchar() ) != EOF ) {
        char const * found, * source = "abc", * dest = "xyz";
        if ( ( found = strchr( "abc", c ) ) != NULL ) {
            putchar( dest[ found - source ] );
        } else {
            putchar( c );
        }
    }
    return 0;
}
Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
0

If you have a lot of characters that you want to replace with other characters (like a Caesar cypher) you can build a lookup for yourself as follows:

#include <string.h>

char plain[] = "Hello there good people";
char encoder[26] = "ghijklmnopqrstuvwxyzabcdef";
char secret[100]; // long enough

int n = strlen(plain);

for(ii = 0; ii < n; ++ii) {
  secret[ii] = encoder[(tolower(plain[ii]) - 'a')%26];
}
secret[n] = '\0';

This uses a couple of tricks:

  1. cast all characters to lower case
  2. subtract 'a' from the lowercase number - since a char is really just a number, we now have a == 0
  3. Perform a modulo operation on the result so things that fall outside of the range of good characters don't cause a memory access error.
  4. Add a '\0' at the end to make sure the string is properly terminated.
  5. Copying things into a new string; obviously you could do an in-place replacement.

As written this will turn numbers (digits) and punctuation / symbols / spaces into characters. You could decide that anything that is not a letter is maintained - and maybe that only lower case letters are converted. In that case

#include <string.h>
char plain[] = "Hello there good people";
char encoder[26] = "ghijklmnopqrstuvwxyzabcdef";
char secret[100]; // long enough

int n = strlen(plain);

for(ii = 0; ii < n; ++ii) {
  if(plain[ii] >= 'a' && plain[ii] <= 'z') {
    secret[ii] = encoder[plain[ii] - 'a'];
  }
  else {
    secret[ii] = plain[ii];
  }
}
secret[n] = '\0';
Floris
  • 45,857
  • 6
  • 70
  • 122
0

there is no such function, you have to write one using strstr. if you can use std::string, you can use string.replace()

wacky6
  • 135
  • 3
-1

Say you want to replace: A with z and b with X

char *replace(char *src, int replaceme, int newchar)  
{
    int len=strlen(src);
    char *p;
    for(p=src; *p ; p++)
    {
       if(*p==replaceme) 
           *p=newchar;
    }
    return src;
}

usage:

 replace(string, 'A', 'z');
 replace(string, 'b', 'X');

This is just the logic to do it, you need more statements in your code.

jim mcnamara
  • 16,005
  • 2
  • 34
  • 51
  • Hi, @jim. I get a Bus Error calling replace in the following example: `char *string = "aAbBcC"; replace(string, 'A', 'z');` – Darren Stone Dec 15 '13 at 05:06
  • 1
    Followup... Declaring and initializing `char string[7] = "aAbBcC";` avoids the error. My bad. C1x tells us that modifying such a string will result in undefined behaviour. Your code is solid. Cheers. – Darren Stone Dec 15 '13 at 05:26
  • You can thing of `char *something = "my string";` as really being `const char *something...` - pointing to read-only memory. You figured it out though. – Floris Dec 15 '13 at 20:17
  • Any reason why you are using `int` rather than `char` to pass characters to the function? Is it because parameters on the stack get aligned anyway? – Floris Dec 15 '13 at 20:17
  • @Floris Yes. You may have noticed that headers for the std C library do the same ex: ctypes.h: int _EXFUN(isalnum, (int __c)); gcc 4.8.2, the arguments get aligned anyway. – jim mcnamara Dec 16 '13 at 01:04
  • @jimmcnamara that's interesting. I had never given it much thought. Is it actually faster than using a prototype with `char` (either way a conversion happens)? I prefer `char` just to keep things readable (it reminds me what I'm passing). But I'm willing to learn new tricks... – Floris Dec 16 '13 at 01:09
  • @Flors This explains char and short promotion to an int: http://icecube.wisc.edu/~dglo/c_class/promo_conv.html – jim mcnamara Dec 16 '13 at 01:46