Home > Software engineering >  How to find the position of the first blank in a string
How to find the position of the first blank in a string

Time:09-21

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

CodePudding user response:

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/

CodePudding user response:

So If I have understood this questions correct, then I think you have been given array of names which contains fname and lname seperated by blank.

Example:

["Amit Kumar", "Riya Jain", "Rohit Sharma"] etc.

And now you have to create two array one for fname and second one for lname.

Example:

fnames -> ["Amit", "Riya", "Rohit"]

lnames -> ["Kumar", "Jain", "Sharma"]

Solution

So now you can create two array fnames and lnames, and iterate through the given array of names and for every element store the name before space in fnames and the name after space in lnames.

You can use split function to get fname and lname where space(" ") is seperator.

  • Related