How to find the position of the first blank in a string

Viewed 42

So I have an array of names and I need to find the position of the blank and put anything that comes before it into fname and put everything that comes after the blank into lname. I have absolutely no idea what I'm doing and I got help from my teacher and she gave me the 3 lines of code that come after posit_of_blank, fname and lname and said that all I had to do was figure out what goes in place of the ... and I haven't got a clue.

using namespace std;
#include "PersonNameFileCreator.h"
#include "PersonName.h"

int main()
{
  string arr_names[] = {"Adam Burke", "Madeline Kramer", "Scott Gardner", 
                        "Tonya Lopez", "Christoper Hamilton", 
                        "Andrew Mitchell", "Lori Smith" };

  PersonNameFileCreator fil_names("names.txt);
  
  for (auto one_name : arr_names)
  {
    int posit_of_blank = ?
    string fname = ?
    string lname = ?
    PersonName onePerson(fname, lname);
    fil_names.write_to_file(onePerson);
  }

  return 0;
}
1 Answers

If you refer to the std::string documentation, it will have what you need.

Given a string std::string name = "Justin Jones" you can find the space using the std::string::find() or the std::string::find_first_of() function. From the example above, you can find the space with unsigned int spacePosition = name.find(" ");. This will return the position of the space and then you can use the std::string::substr function to split it where you need it.

Here is a link to the find function: https://cplusplus.com/reference/string/string/find/

Here is a link to the substr function: https://cplusplus.com/reference/string/string/substr/

Related