Replace string chars

Started by
8 comments, last by penetrator 21 years, 3 months ago
Which function and header do i need to replace characters in a string ?
www.web-discovery.net

Advertisement
I''m using VC++ and no MFC ...



www.web-discovery.net

are you using stl strings or char*

dunno about std::strings but for char* such a function doesnt exist, but its trivial to write one yourself:


        char kill = 'a';char replace = 'z';for ( int i = 0; i < strlen(str); i++ )    if ( str[i] == kill )         str[i] = replace;        


this will replace all 'a' with 'z' when str is either char* or std::string when you replace strlen(str) with str.length()


Runicsoft -- latest attraction: obfuscated Brainfuck Interpreter in SML

This post was made entirely from re-cycled electrons


[edited by - Burning_Ice on January 19, 2003 9:10:55 AM]
and if i should replace, for example, "......" with "..", what the code would be ?



www.web-discovery.net

Hey, Your .sig is too big!

Now...
quote:Original post by penetrator
and if i should replace, for example, "......" with "..", what the code would be ?

In that case you're creating a new string (".." is shorter than "......"), so it's not just a matter of replacement.

    char * found = 0;char formed[60] = {0};const char text[60] = "Some very long string incorporating a...... triple ellipsis";const char * trellipsis = "......"; found = strstr( text, trellipsis );if( found != 0 && found != text ){  strncpy( formed, text, (found - text) );  strcat( formed, ".." );  strcat( formed, (found + 6) );}    

And that is why you should use std::string.

[edited by - Oluseyi on January 19, 2003 11:50:33 AM]
Still not working. All i want to do is to store string values which are separated by spaces, sometimes 2, sometimes 4 or 5 spaces, into 1 array. So just imagine the string is smt like this:

char mystring[8192]="1 4 6 7 2";

i want to store values into a simple array, so that i get smt like:

myarray[1]=1;
myarray[2]=4;
myarray[3]=6;
myarray[4]=7;
myarray[5]=2;

I was used to to this in VB very easily with a Split function, but in VC++ i''m lost !

#include <sstream>

int main() {
char mystring[8192]="1 4 6 7 2";
std::stringstream s;
s << mystring;
int a[5];
for (int i=0; i<5; ++i)
s >> a;
}

  #include <sstream>int main() {  char mystring[8192]="1 4 6 7 2";  std::stringstream s;  s << mystring;  int a[5];  for (int i=0; i<5; ++i)    s >> a[i];}  
quote:Original post by penetrator
Still not working. All i want to do is to store string values which are separated by spaces, sometimes 2, sometimes 4 or 5 spaces, into 1 array...

In the future, say what you want to do. It saves both us and you time explaining stuff that doesn''t solve your problem.
Excuse, i will be more precise ! Thanks for help.

This topic is closed to new replies.

Advertisement