Hellochina, I rarely use C++ but yesterday I came up with an idea for a program. What I want to happen is for the program to take a string, and for every letter, replace it with something else (for example, the letter after, or the number of the letter in the alphabet, eg. d would be come e or 04). I want to do this for every letter in the string, so basically its a find and replace program. I think I could code it if I knew what to do, I'm just unsure how I could do this with <string>.find and <string>.replace.

I would like you to respond saying how I could do this but without telling me the code (or just put the code in a spoiler or something so I could try it myself first.)

Thanks.

Recommended Answers

All 24 Replies

Sorry, I don't understand any of that...

I tried this, but it didn't work. What I was trying to do was replace all a's in the string with 01. It lets me enter text, but as soon as I press enter, this comes up:

"This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information."

Code:

#include <iostream>
#include <string>

using namespace std;

    string string1;
    int stringlen;
    int replpos;

int main(){
    
    cout << "Enter some text: ";
    getline(cin, string1);
    
    stringlen = string1.size();
    
    
    while(int x = 0 <= stringlen)
    {
              replpos = string1.find("a");
              string1.replace(replpos, 1, "01");
              x = x + 1;
    }
    
    cout << string1;
    
    system("PAUSE");
    
}

I just noticed line 18, I don't think that would work... x = 0 <= stringlen

Changed to this:

#include <iostream>
#include <string>

using namespace std;

    string string1;
    int stringlen;
    int replpos;
    int a = 0;

int main(){
    
    cout << "Enter some text: ";
    getline(cin, string1);
    
    stringlen = string1.size();
    
    
    while(a <= stringlen)
    {
    replpos = string1.find("a");
    string1.replace(replpos, 1, "01");
    a++;
    }
    
    cout << string1;
    
    system("PAUSE");
    
}

But now this doesn't compile...

Errors:

Permission denied
Id returned 1 exit status
file: C:\Dev-Cpp\Makefile.win [Build Error] [aerobic.exe] Error 1

Not sure with the compile error what is wrong, maybe you were trying to build it with the program still running. As far as what your code you are very close. I won't give you the answer since you want to figure it out on your own but here is a hint.

#include <iostream>
#include <string>

using namespace std;

    string string1;
    int stringlen;
    int replpos;
    int a = 0;

int main(){
    
    cout << "Enter some text: ";
    getline(cin, string1);
    
    stringlen = string1.size();

    replpos = string1.find("a");
    cout << replpos;
    //run this part a few times first type something with an 'a' in it
    //what is the value and why? Now run again with something without an 'a'
    //what value are you at now? That should clear your understanding up a bit
         
    return 0;
    
}

Nah I have absolutely no idea what to do... I understand that the replpos is the character number of the first letter a (eg. string1 = abcde, replpos = 0) and replpos = -1 if there isnt an a. I just dont see how this could help or what I'm supposed to do next...

Ugh... I just want the code now, and an explanation of it please.

Think I've gotten a bit closer now:

#include <iostream>
#include <string>

using namespace std;

    string string1;
    int stringlen;
    int replpos;
    int x = 0;

int main(){
    
    cout << "Enter some text: ";
    getline(cin, string1);
    
    stringlen = string1.size();
    
    
    while(x < stringlen)
    {
              replpos == string1.find("a");
              string1.replace(replpos+1, 1, "01");
              x++;
              
    }
    
    cout << string1;
    
    system("PAUSE");
    
}

If I enter something like "programming", I get "p011111111111ogramming". Pleeeeeeeeeease help!!!

Your code does not work mainly for two reasons..
Firstly, line 21:

replpos == string1.find("a");

You are not assigning any value for replpos, just comparing the values of replpos and string1.find("a"). "==" is for comparison and "=" is for assigning..

Secondly, the next line, line 22:

string1.replace(replpos+1, 1, "01");

Why that extra '1'? The place where you find your 'a' is replpos, there is no point in adding 1 to it.
Effecting just these two changes should get you going smoothly...

Note: If 'a' is not found then string.find returns 'string::npos', you must watch out for that as well. Otherwise the program aborts.

Ok let me explain a little further when I had you run that test it was because if an a is not found it will return -1 in most programming that return value means just that nothing was found or false. The reason I bold if that is your keyword. In your revised code line 21 is wrong don't use == that is for comparison. Try to read your program out in english first then translate to code. The problem is in your loop.

while x is less than the length of the string
//change back to what it was replpos = string1.find("a");
put the value of the funtion string.find() into the variable replpos
this line you are attempting replace i belive it was right the first time to
next add 1 to the value x
retarts loop

So what you are doing is saying for the entire length of the string loop and find "a" and replace it at this spot. The way I did it was using an if statement inside the loop. And I used the handy fact that -1 is thrown if it's not found as my comparison. Give it one more try with that info. If it's still making you want to pull your hair out after that I'll post code, but you will feel more rewarded doing it yourself.

@britanicus The only time I found this script to abort was if "a" is not found and you use the value -1 in the replace function as -1 is supposed to mean not found in the sense of string::find. In the sense of string::replace -1 is non-existant thus the crash.

Yay thank you for that information, I got it :D

#include <iostream>
#include <string>

using namespace std;

    string string1;
    int stringlen;
    int replpos;
    int x = 0;

int main(){
    
    cout << "Enter some text: ";
    getline(cin, string1);
    
    stringlen = string1.size();
    
    
    while(x < stringlen)
    {
              replpos = string1.find("a");
              if (replpos == -1){
                          break;
              }
              else{
              string1.replace(replpos, 1, "01");
              x++;
              }
              
    }
    
    cout << string1;
    
    system("PAUSE");
    
}

edit: off topic, but I'm adding this for more letters now, and line 76 of code is:

c++;

:)

Nice job :) c++ is new for me to but it's slowly starting to look more like english.

C++ is not hard! I am trying to learn Assembly now :p

My heart and soul may travel with you then brother lol.

Something else I just realised, if I had a string and converted it to numbers, how would I convert those back into letters?

eg. the word "all" is entered and it spits out 011212

Is it possible to check the first 2 numbers and then convert those back to letters?

eg. It would check to see what the first 2 numbers are, and then convert those back to a letter. Something like:

int replpos2 = 0;

<insert other code here>

if(string1.first2numbers == 01){

    string1.replace(replpos2, 2, "a");
    replpos2 += 2;

}

Then do the same for numbers 3/4, then 5/6 etc...

Consider what the following might do:

char letter = 'q';
int order = letter - 'a';

...

char other_letter = 'a' + other_order;

And as for your question about reading successive 2-digit numbers:

...
std::string next_num = std::string(string, pos, 2);
pos += 2;
int value = strtol(nex_num.c_str());
...

I'm sure there's a more C++-ish way to do that last line, maybe using a strstream, but I'm old-school and learned C before C++ was stable enough to be usable, so I have lots of "bad" habits.... :)

Hmm... Don't really understand the above post...

Something else I want to happen is for it to change numbers into other numbers

eg. 0 changes to 26051815, 1 changes to 151405. I used this code:

while(zero < string1.size()){
                             
                       replpos = string1.find("0");
                              
                              if (replpos == -1){
                                 break;
                              }
                              else{
                                  string1.replace(replpos, 1, "26051815");
                                  zero+=9;
                              }
                 }  
                 
                 while(one < string1.size()){
                             
                       replpos = string1.find("1");
                              
                              if (replpos == -1){
                                 break;
                              }
                              else{
                                  string1.replace(replpos, 1, "151405");
                                  one+=7;
                              }
                 }

But when I enter 01, instead of getting 26051815151405 out, I get 26262626262626262626262626260515140551405514055140551405514055140551405514055140
55140551405514055140551405514055140551405514055140551405514055140551405514055140
55140551405514055140551405514055140551405514055140551405514055140551405514055140
55140551405514058155181551815518155181551815518155181551815518155181551815518155
1514055140551405514055140581512

No idea why, please help. Also thanks for all of the help I've already gotten.

I don't know why you're using variables zero and one in addition to replpos , so first of all, <frequent advice>slow down, think through what it is you're trying to do, say it out loud or write it down clearly in English (or your natural language of choice), and then code it from there.</frequent advice>

In your case, you're looking for and replacing successive digits. While you can certainly do this in-place in a single string, it might be simpler to build a second string while you go through the first.

However, your algorithm should be something like:

while i'm not at the end of my string:
    find the next zero or one, whichever comes first
    if it's a zero:
        replace it with the zero-replacement string
        advance the position by the length of the replacement
    if it's a one:
        replace it with the one-replacement string
        advance the position by the length of the replacement

I think you have an off-by-one error in your increments, you only need to update replpos, and instead of two different blocks (which, the way you have them now, will only work if successive values of 0 and 1 alternate in your original string), you need to do two separate finds and keep the answer with the smallest position. Does that make sense?

Aside: if your replacement strings are all different lengths, you may have quite a challenge reversing your "encryption". As an overly simple example, if you encode 'a' by 123, 'b' by 456, and 'c' by 1234, then 'ab' encodes to 123456. But if you're decoding a string that starts with 123456..., does it start with 'ab' or 'c'? A commonly used compression technique (based solely on frequency of values, not on patterns within sets of values) is Huffman encoding. It ensures that any string of encoded values has a unique decoding, and that the encoding is of minimal length. I bet there's a good entry in wikipedia, if you want to learn more. Meanwhile, happy encoding!

Erm... I'm still not sure what I'm supposed to do.

What I want it to do is...

while its not at the end of the string,
    find the first 0
    replace it with 26051815
    continue searching for 0's starting from the end of the 26051815 (so it doesnt replace the 0 there)


    find the first 1
    replace with 151405
    skip ahead 6 (7?) characters and continue


    find the first 2....etc.

I thought that is what this code should do, but it doesn't seem to work and I can't figure out why.

while(zero < string1.size()){
                             
                       replpos = string1.find("0");
                              
                              if (replpos == -1){
                                 break;
                              }
                              else{
                                  string1.replace(replpos, 1, "26051815");
                                  zero+=9;
                              }
                 }  
                 
                 while(one < string1.size()){
                             
                       replpos = string1.find("1");
                              
                              if (replpos == -1){
                                 break;
                              }
                              else{
                                  string1.replace(replpos, 1, "151405");
                                  one+=7;
                              }
                 }

try putting this

while(x < stringlen)
{
    letter=string1.at(x);

    if(letter=='a'){
          //replpos == string1.find("a");
          string1.replace(x,1,"01");
    }
    x++;
 }

Yay I got it to work with the help of the above post :D Thanks for that, I had never seen <string>.at(pos) before.

Ok, the last thing (I think) that I need to be able to do is search for a string within another string....help?

try looking at msdn for the string class methods

string::find does do that buddy. I know this stuff is hard to read, but you should start learning now, if we give a man a fish we feed him for a day, if we teach a man to fish we feed him for a lifetime. Now grant it I am not great at this either but I am forcing myself to learn and possibly we can get a better answer from some uber smart peeps here.

Now let me refer you back here string::find.
Ok at the top this line
size_t find ( const string& str, size_t pos = 0 ) const;
Ok this is the first version of string::find method.
There is another thing of intrest for us noobs below.

Find content in string

Searches the string for the content specified in either str, s or c, and returns the position of the first occurrence in the string.

When pos is specified the search only includes characters on or after position pos, ignoring any possible occurrences in previous locations.

So if we search for str it will return the position at which if finds str(or string).

So you see the very first version shows us we can search for a string inside a string. Look to the example below it shows the diffrent versions of string::find in order of descriptions we just looked at.

found=str.find(str2);
in english then this means found will be assigned the value of the position where we located string2 inside of string1.

Remember to read everything as many times as you need to read it fully and try to understand it. Also you have examples so don't be scared to use them and play around with them, the more you do the more the c++ jibberish will start making sence. And the less you will need to rely on others for help. I don't think anybody minds helping you but you will be able to accomplish more if you can help yourself as well. Believe me I know this first stage is difficult. You have to do what they call breaking the wheel. Your brain will be much for quite some time, and then boom you will have a small breakthrough and understanding. After that more brain mush, after that boom a great breakthrough and you will understand most things.

Some of the best advice I can give is read those manuscripts all the way through, test code, go back read again, if you are following any tutorials go back and scan through any sections regaurding strings, read manuscript again. The main thing to remember when your brain turns mushy go make some coffee or do what you do for a break. Mush first then break, when you are in break mode is when anwsers come.

I also will offer to help or mentor you along although I am still learning myself. Feel free to contact me at my personal email williampolatis@yahoo.com. Please put c++ buddy or something similar in the subject line if you would like further personal help from me. Thank you and best of wishes in your coding endevors freind.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.