So, as you can see...

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

int main() 
{
    char comma = ',';
    string str1 = "hello,friend";
    string str2 = str1.substr(str1.find(comma)+1, str1.length()); //i guess this line...
    cout << str2 << endl;
    system("pause");
    return 0;
}

What is being output is str2, and it is a substring of str1. It finds the comma, and erases it and any other characters after. This outputs "friend". But what I want is instead of removing the characters after the comma, the characters before comma would be removed. So the data "hello" will be output instead.

Thanks...

Edited 5 Years Ago by Tom_Weston: n/a

The first parameter of substr() is where you want to start so you don't want to start at the comma. you want to start at zero and go untill there is a comma. To do that you can do this.

string str1 = "hello,friend";
string str2 = str1.substr(0, str1.find(","));

this example will not delete any of the contents of str1 it will only copy the part before the comma into str2

Comments
Extremly Helpfull, Thank you for your contribution!

Try googling C++ string erase.

Dude have you even tried my code? "hello," is gone and friend remains. Now, all i want is ",friend" gone and hello to remain.

Anyone else?

The first parameter of substr() is where you want to start so you don't want to start at the comma. you want to start at zero and go untill there is a comma. To do that you can do this.

string str1 = "hello,friend";
string str2 = str1.substr(0, str1.find(","));

this example will not delete any of the contents of str1 it will only copy the part before the comma into str2

Thanks for the quick reply Nathan, will take a look at your example given!

EDIT : Thank you Nathan, your post was extremely useful, and it works! :D

Edited 5 Years Ago by Tom_Weston: n/a

Dude have you even tried my code? "hello," is gone and friend remains. Now, all i want is ",friend" gone and hello to remain.

Anyone else?

Actually nothing is gone. All you did was take a section of the string and create another string from it....dude.

#include <iostream>
    #include <string>
    using namespace std;
     
    int main()
    {
    char comma = ',';
    string str1 = "hello,friend";
    string str2 = str1.substr(str1.find(comma)+1, str1.length()); //i guess this line...
    cout << str2 << endl;
    cout << "original string->" << str1 << std::endl;
	//system("pause");
    return 0;
    }
This article has been dead for over six months. Start a new discussion instead.