replacing string

closed account (N8RzwA7f)
Hi,
can someone help me ? I've been trying to solve this for 3 days :( I need to replace an upper case abbreviation like LOL to lowercase in the tweet.
so that : hi there LOL i will TTYL
becomes: hi there laughing out loud i will talk to you later


thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 /* 
 * File:   main.cpp
 * Author: Melissa
 *
 * Created on den 12 december 2015, 19:38
 */

#include <cstdlib>
#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main() {
 string tweetArray[] = {"LOL","IRL","AFK","NVM","BFF","FTW","IIRC","TTYL","IMHO"}; 
 string strArray[] = {"laughing out loud","in real life","away from keyboard","never mind","best friends forever","for the win", "if i recall correctly","talk to you later","in my honest opinon"};

 string tweet2;
 cout << "enter a tweet: " << endl;
 getline(cin,tweet2);

 int charnum = 0;
 bool found = true;
 int location = 0;
 
 while (found){
     if(location == 0){
           location = tweet2.find(tweetArray[charnum]);
           tweet2.replace(location,tweetArray[charnum].length(),strArray[charnum]);
     } else {
           location = tweet2.find(tweetArray[charnum],location);
           tweet2.replace(location,tweetArray[charnum].length(),strArray[charnum]);
           ++charnum;
           if(charnum >= 10){
               found = false;
           }
     }   
 }  
 cout << tweet2;            
 return 0;

}

I don't see where you are checking for the not-found condition
(find() will return string::npos).
http://www.cplusplus.com/reference/string/string/find/

Declare location as unsigned.
unsigned int location = 0;
Then maybe just use a for-loop to search for each item in turn.
Inside the for loop,
1
2
    while (string::npos != (location = tweet2.find(tweetArray[charnum])))
     // replace abbrev with full text.  




closed account (N8RzwA7f)
That did it thanks. So why did it not work before? Only because I forgot to check for npos?
I had tried many times with a for loop and it didn't work .
Why did it not work before? I'm not sure. I ran the original code unchanged and it crashed with an out-of-range error which I guessed might have been due to either this: if(charnum >= 10) or trying to access an invalid location in the string. I didn't bother to find out, as without the npos test it was almost certainly wrong, but also the code looked overly complicated so I re-wrote that last part - except for the replace() statement which was fine.

Actually I can see that your code was probably (if working) better optimised, my suggestion always starts from the beginning. But that's easily fixed
Last edited on
Topic archived. No new replies allowed.