Advertisement

OT: search and replace chars in string with C++

Started by January 19, 2003 10:05 AM
11 comments, last by penetrator 22 years, 1 month ago
In VB i''d use a simple Replace function, but i''m new to C++ so excuse me for all these questions ... I''d like to search a string and replace chars. This is my code, but i get several errors when i compile, can you help me ? char kill[6]; strcpy(kill, "------"); char replace[2]; strcpy(replace, "--"); for (int i=0; i
www.web-discovery.net

if (mystring[i+6]== kill) { mystring[i+2]= replace; }


Advertisement
I''m tryng to read single chars from a string, buti get errors. Take a look at this code:

char project_geo_temp[7];
char singlechars[7][1];
strcpy(project_geo_temp, "Testing";

z=strlen(project_geo_temp);

for (int i=0; i{
sscanf(project_geo_temp, "%1c", singlechars);<br>}<br><br>What i would like to get is an array like :<br><br>singlechars[1] = T;<br>singlechars[2] = e;<br>singlechars[3] = s;<br>singlechars[4] = t;<br>singlechars[5] = i;<br>singlechars[6] = n;<br>singlechars[7] = g; </i> <br><br>
quote:
char singlechars[7][1];


you declared singlechars as a 2 dimensional array. Therefore you have to acess it 2 dimensionally(ie singlechars[1][0], singlechars[2][0]).

It seems point less to have arrays of size one tho. What you have done is created an array of 7 arrays of size 1. It''s rather pointless to have an array of size one so you should just use singlechars[7].
for (int i=0; i{
sscanf(project_geo_temp, "%1c", singlechars);
}

.
/ \
|
|

That doesn''t look like a correct for loop syntax.
no, sorry that''s a type, the code is:

char project_geo_temp[7];
char singlechars[7][1];
strcpy(project_geo_temp, "Testing";

z=strlen(project_geo_temp);

for (int i=0; i{
sscanf(project_geo_temp, "%1c", singlechars);
}

What i would like to get is an array like :

singlechars[1] = T;
singlechars[2] = e;
singlechars[3] = s;
singlechars[4] = t;
singlechars[5] = i;
singlechars[6] = n;
singlechars[7] = g;


Advertisement
well, copy and paste dont work, anyway the for instruction is :

for (int i=0; i
Finding and replacing chars in a string with c++:

string s = "something foo something";
int position = s.find("foo");
s.replace(position, 3, "pie");


If the substring is not found, then find will return string::npos - be sure to check for this when necessary. By the way, this topic might have been better off in the general programming forum.
Yes, i should have posted this in the programming forum. Which header do i need to use string replace funtion ?

#include <string> (no .h) allows you to use the std::string type. If you only want to type string instead, then also add the line using std::string; or using namespace std; after the #include.

This topic is closed to new replies.

Advertisement