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...

Try googling C++ string erase.

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

commented: Extremly Helpfull, Thank you for your contribution! +1

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

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;
    }
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.