![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Hobbyist Programmer
Join Date: Mar 2005
Posts: 148
Rep Power: 4
![]() |
Replacing a word with another word
This probably is going to be just one of several questions I'm going to ask regarding this program. The program has a string of text, and then replaces a word with another word. But to start with all I'm trying to do here is just output the index positions of the word "rose". Here is the program:
int main()
{
string text = "A rose is just a rose is a rose.";
string word = "rose";
string replacement = "thorn";
int start = text.find(word);
cout << start << endl;
while (start != string::npos)
{
text.replace(start, word.length(), replacement);
start = text.find(word);
cout << start << endl;
}
return 0;
}When I run the program it outputs the following: 2 18 29 -1 But I was expecting it to output the following: 2 17 27 Because the index position of the first occurrence of the word "rose" is found at index position 2. Then if you keep counting, the second occurrence of the word "rose" is found at index postion 17. And the final occurrence of the word "rose" is found at index position 27. And I don't know what the -1 is for either(maybe that is the illegal character position that is returned when the while test condition eventually fails). |
|
|
|
|
|
#2 |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
Surely you realize that if the word, "rose", is replaced by the word, "thorn", then every subsequent character moves to a position one greater than before. Your next find operation works on the NEW text, not the old text.
Incidentally, have you checked on the value of string::npos in your environment?
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Word Frequency Regular Expression | hoffmandirt | C# | 4 | Feb 27th, 2006 8:21 PM |
| How to determine if it's a word | aznluvsmc | C | 10 | Aug 22nd, 2005 11:30 AM |
| Help with sorting and counting? | mmmm_strawberries | C++ | 8 | Apr 3rd, 2005 6:47 PM |
| crack these questions if u can!!! | shagan | C++ | 18 | Apr 3rd, 2005 6:47 AM |
| how to implemen the Find funtion in the text editor to locate a word in a document??? | allen1984us | C++ | 4 | Mar 8th, 2005 10:32 AM |