user3395662
user3395662

Reputation: 95

Create a new string from prefix up to character position in C++

How can I find the position of a character in a string? Ex. If I input "abc*ab" I would like to create a new string with just "abc". Can you help me with my problem?

Upvotes: 5

Views: 38616

Answers (4)

ggorlen
ggorlen

Reputation: 56865

Elaborating on existing answers, you can use string.find() and string.substr():

#include <iostream>
#include <string>

int main() {
    std::string s = "abc*ab";
    size_t index = s.find("*");

    if (index != std::string::npos) {
        std::string prefix = s.substr(0, index);
        std::cout << prefix << "\n"; // => abc
    }
}

Upvotes: 0

Victor
Victor

Reputation: 14573

If you are working with std::string type, then it is very easy to find the position of a character, by using std::find algorithm like so:

#include <string>
#include <algorithm>
#include <iostream>

using namespace std;

int main()
{
    string first_string = "abc*ab";
    string truncated_string = string( first_string.cbegin(), find( first_string.cbegin(), first_string.cend(), '*' ) );

    cout << truncated_string << endl;
}

Note: if your character is found multiple times in your std::string, then the find algorithm will return the position of the occurrence.

Upvotes: 0

6502
6502

Reputation: 114461

C++ standard string provides a find method:

s.find(c)

returns the position of first instance of character c into string s or std::string::npos in case the character is not present at all. You can also pass the starting index for the search; i.e.

s.find(c, x0)

will return the first index of character c but starting the search from position x0.

Upvotes: 8

user1508519
user1508519

Reputation:

std::find returns an iterator to the first element it finds that compares equal to what you're looking for (or the second argument if it doesn't find anything, in this case the end iterator.) You can construct a std::string using iterators.

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::string s = "abc*ab";
    std::string s2(s.begin(), std::find(s.begin(), s.end(), '*'));
    std::cout << s2;
    return 0;
}

Upvotes: 6

Related Questions