-1

I have a quick question about strings and how it can be viewed one character at a time, but I'm having troubles figuring out how to stop reading from a string after the second time. I have a email "firstname.lastname@whatever.com" and I've successfully extracted the firstname to my first string, the second string I'm at a complete loss of what I should do, the best I've gotten was "FirstName Lastname@whatever.com"

What I would like to happen is its just grabs the string and drop whatever is left after the '@' character.

`

FirstName = "";
    LastName = "";
    string::size_type i;
    for (i = 0; !ispunct(Email.at(i)); i++)
        FirstName = FirstName + Email.at(i);

    for (i = i + 1; !ispunct(Email.length()); i++) // this right here ends up as "LastName@whatever.com"
        LastName = LastName + Email[i];

`

I know I have to use !ispunct() but I'm just confused as of where or even how it works

Thanks in advance

TBG
  • 1
  • Does this answer your question? [Parse (split) a string in C++ using string delimiter (standard C++)](https://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c) – kotatsuyaki Nov 23 '22 at 05:57
  • Why have you changed the other loop condition? – 273K Nov 23 '22 at 05:59

1 Answers1

0

Basically you know already, how to iterate over a std::string. Examples:

  • You can use a normal for or while or do loop and acess elements of the std::string via its index operator [] or with the atfunction
  • You can use a simple range based for loop
  • Iterators
  • Or, one of many functions from the algorithm library or
  • Many more

But, what you want to do is to split a string. There are really many possibilities. A very popular approach is to put the std::string into a std::istringstream and then use std::getline with a delimiter to extract part by part.

I personally like the std::sregex_token_iterator, but let's at first stick to the getline-solution.

Please she example below:

#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string emailAddress{ "firstname.lastname@whatever.com" };

    std::string firstName{};
    std::string lastName{};
    std::string domain{};
    std::string extension{};

    // Put string into stringstream, to be able to extract parts
    std::istringstream iss{ emailAddress };

    // Extract all parts
    std::getline(iss, firstName, '.');
    std::getline(iss, lastName, '@');
    std::getline(iss, domain, '.');
    std::getline(iss, extension);

    // Show single parts:
    std::cout << firstName << '\n' << lastName << '\n' << domain << '\n' << extension << '\n';
}
A M
  • 14,694
  • 5
  • 19
  • 44