c++11 - adding new options to my String class
Oct 8, 2014 at 4:23pm UTC
i'm give the replace option to my string:
1 2 3 4 5
void replace(string oldstring, string newstring)
{
int stroldstringpos=b.find(oldstring);
b.replace(stroldstringpos,newstring.length(),newstring);
}
i have 1 error in these function that i'm confused. imagine the newstring size is more big than the oldstring, how can change the string, but only change the oldstring and add what left?
see these:
1 2
String test="hi hello world" ;
test.replace("hi" ,"hello" );
the result must be:
hello hello world
how can i change the replace function for it?
Oct 8, 2014 at 4:39pm UTC
Replace only amount of characters you need to replace. Thois would be size of oldstring. Why do you use size of newstring in the first place?
Oct 8, 2014 at 4:53pm UTC
thanks for correct me ;)
Oct 8, 2014 at 5:32pm UTC
1 2 3 4 5 6 7 8 9 10
void replace(string oldstring, string newstring)
{
int stroldstringpos=b.find(oldstring);
b.replace(stroldstringpos,oldstring.length(),newstring);
}
void replace(int stringpos, string newstring)
{
b.replace(stringpos,newstring.length(),newstring);
}
heres a nice way for get some part of the string:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
string left(int StringPos, int StringLength)
{
string s="" ;
int i=StringPos;
int length=0;
if (StringPos>b.length()) StringPos==b.length()-1;
if (StringPos+StringLength>b.length()) StringLength==0;
for (i=StringPos,length=0; length<StringLength; i++,length++)
{
s=(string)s+b[i];
}
return s;
}
for get the right and left position of the string:
1 2 3 4 5 6 7 8 9
int lfind(string strword)
{
return b.find(strword);
}
int rfind(string strword)
{
return b.rfind(strword);
}
and a nice one for separe the words:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
vector<string> separewords()
{
vector<string> words;
int i=0;
int stringlength=b.length();
string s="" ;
for (i=0;i<stringlength;i++)
{
if (b[i]== ' ' || b[i]== '\n' )
{
if (s!="" )
words.push_back(s);
s="" ;
}
else
{
s=(string)s+b[i];
}
}
//by some reason i'm getting problems for put it on 'else'
if (s!="" )
words.push_back(s);
return words;
}
with more little update and i can, maybe, separe for code or others ;)
Topic archived. No new replies allowed.