string

A

amarnath subbiah

hi, i want to know the built-in function for extracting and replacing
a substring in a string.
i suppose it should be done using a sequence of built-in functions,,
pls help me
 
V

Victor Bazarov

amarnath said:
hi, i want to know the built-in function for extracting and replacing
a substring in a string.

Extracing - 'substr' member in 'std::string'. Replacing - there is
no simple one-shot deal, use 'insert' after 'erase'.
i suppose it should be done using a sequence of built-in functions,,

Yes.

V
 
H

hurcan solter

ng in a string.
Extracing - 'substr' member in 'std::string'. Replacing - there is
no simple one-shot deal, use 'insert' after 'erase'.
something like this;

#include <iostream>
#include <string>
using namespace std;
int main()
{
string text = "dog bites cat";
string substring = "bites";
std::size_t pos=text.find(substring);
if(pos != string::npos)
text.erase(pos,substring.length()).insert(pos,"loves");
cout<< text;
}
 
P

ppi

#include <iostream>
#include <string>
using namespace std;
int main()
{
string text = "dog bites cat";
string substring = "bites";
std::size_t pos=text.find(substring);
if(pos != string::npos)
text.erase(pos,substring.length()).insert(pos,"loves");
cout<< text;

}

what about:
text.replace( pos, substring.length(), "loves" );
 
H

hurcan solter

what about:
text.replace( pos, substring.length(), "loves" );

seem like you are right . I always thought 'replace' replaces UPTO
substring.length of characters. if replacement string is smaller than
the replaced string the excess characters will remain in the
string.But apparently that is not the case.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,176
Messages
2,570,947
Members
47,501
Latest member
Ledmyplace

Latest Threads

Top