Home > Net >  Replacing a pair of characters in a string with another
Replacing a pair of characters in a string with another

Time:11-16

I want to replace a pair of characters with another pair.

For example if want to replace "ax" with "57" and the string is "vksax", it will give out "vks57".

Tried it this way but get a weird output that is only partially correct:

#include <stdio.h>
#include <stdlib.h>

int main()
{
   
char dummy;
int i;
char string[16];
scanf("%s", string);

for(i=0;string[i];i  ){
  if(string[i] == 'a'  && string[i 1] == 'x'){
    string[i] = '5' ;
    string[i 1] = '7';
    i=0;  
  }
printf("%s", string) ;
}
   exit(0);
}

I can't figure out why it gives, for example, with an input of 1234ax the output 1234ax1234ax1234ax1234ax123457123457123457123457123457123457

CodePudding user response:

Within the for loop

for(i=0;string[i];i  ){
  if(string[i] == 'a'  && string[i 1] == 'x'){
    string[i] = '5' ;
    string[i 1] = '7';
    i=0;  
  }

this statement

i=0;  

does not make a sense. Remove it. And instead of

    string[i 1] = '7';

write

    string[  i] = '7';

And move this call

printf("%s", string) ;

outside the for loop.

Pay attention to that the variable dummy is declared but not used.

char dummy;

Remove this declaration.

And there is no great sense to use exit( 0 ); instead of return 0;.

And the call of scanf will be more safer if to write it like

scanf("s", string);

CodePudding user response:

Since this question is marked as C , here is C one-line answer:

#include <string>
std::string String = "vksax";
String.replace(String.find("ax"), 2, "57");

Get yourself familiar with std::string https://www.cplusplus.com/reference/string/string/

Solution as function(it assumes substring to be replaced and replacement have the same length):

std::string FindAndReplace(std::string sInputString, std::string sReplaceThis, std::string sReplacement)
{
    size_t iPos = sInputString.find(sReplaceThis);
    if(iPos == std::string::npos)
        return sInputString;

    sInputString.replace(iPos, sReplacement.length(), sReplacement);
    return sInputString;
};
  • Related