| srikanth chitturi (37) | |
|
Hi all, I have written a word replacement program in c++. Can anyone write a better solution than this? Because this uses character arrays . #include <stdio.h> #include <iostream> #include <string> #include <vector> using namespace std; int main() { string str; vector<string> a; vector<string>::iterator it; char word[40]; cout<<"Please enter something :"<<endl; gets(word); int pos; int length = strlen(word); // copy the sentence into a vector for(int i=0;i<length;i++) { str.push_back(word[i]); if(word[i] == ' ' || i == length - 1 ) { a.push_back(str); str.clear(); continue; } } cout<<"Please enter another string: "<<endl; cin>>str; cout<<"Enter the position to replace the word:"<<endl; cin>>pos; it = a.begin(); it = a.erase(it+pos); it = a.begin(); a.insert(it+pos,str); for(it = a.begin();it <a.end();it++) { cout<<*it<<" "; } cout<<endl; system("pause"); } | |
|
|
|
| kbw (5375) | |
|
I'm not sure what that's meant to be doing, but it doesn't feel quite right. 1. Why are you using a char[40] for a string when you could use std::string? You use string elsewhere, so why not there? 2. Why are you mixing gets and std::cout? Do you realise that std::cin and std::cout are tied? 3. Please the code format tags to format your code. 4. Please describe what the program is supposed to be doing. | |
|
|
|
| srikanth chitturi (37) | |
|
Output of the program enter the word : I am a girl Enter another string : boy Enter the position to replace the word : 3 I am a boy . This is the output . Brief explanation : I have initially taken the word into a character array and have copied it to a vector<string> , Then I have taken another string. I have finally taken a position value from the user and have replaced the second word with position value . | |
|
Last edited on
|
|
| kbw (5375) | |
|
1. Read the strings into an ordered collection (like a vector). 2. Use the index to identify the element of the collection to be replaced. 3. Overwrite the indexed element with the new word. 4. Write out the sentence from the collection. | |
|
|
|
| vlad from moscow (3112) | |
I already said you in your previous theme how your task can be done simply by using std::istringstream.s.replace( s.find( source ), source.size(), target );All what you need is to extract the source word from istringstream. | |
|
|
|
| JLBorges (1336) | |||
I suppose one shouldn't be just destroying white spaces in the original string.
TO DO: Handle punctuation correctly. "I am - repeat am - a girl." | |||
|
|
|||