-
December 16th, 2008, 11:27 PM
#1
Replace function
The goal is to replace Invalid_Enum with int. The approach.
Code:
# include <string>
# include <iostream>
void
Replace( std::string& Source, const std::string& Replacement)
{
std::string::size_type Pos = 0;
Pos = Source.find( '(' ); Pos++;
std::string::size_type Pos2 = 0;
Pos2 = Source.find ( "Enum" , Pos ) ; Pos2 += 3;
Source.replace ( Pos, Pos2, Replacement );
}
int main() {
std::string test ( "(Invalid_Enum e )" )
Replace ( test, " int" ) ;
std::cout << test << std::endl;
std::cin.get();
}
I'm not sure there's a more efficient way to do this? I suspect one way to do this is to write the replace function to take as arguments the Source string, the Replacement strings, the start and end character (or start and end string) .
-
December 17th, 2008, 12:37 AM
#2
Re: Replace function
Originally Posted by mop65715
The goal is to replace Invalid_Enum with int.
Taking what you say literally, it sounds like you want to write:
Code:
#include <string>
#include <iostream>
void Replace(std::string& subject, const std::string& search, const std::string& replacement)
{
std::string::size_type pos = subject.find(search);
if (pos != std::string::npos)
{
std::string::iterator begin = subject.begin() + pos;
subject.replace(begin, begin + search.size(), replacement);
}
}
int main()
{
std::string test("(Invalid_Enum e )");
Replace(test, "Invalid_Enum", " int");
std::cout << test << std::endl;
std::cin.get();
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|