Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split a string into two strings using a comma, and store the strings? (C++) [duplicate]

Tags:

c++

I looked to see if this had been asked before, but all I got was answers for Java. I have to read first names and last names from a file, in the format of (lastname,firstname). The program requires us to (among other things), display the name in the format of (firstname lastname), with a space instead of a comma. I figured the easiest thing to do would be to split the string into two smaller strings, and then just display them in order. How would I go about doing this? I saw some BOOST token thing, but I can't use that as the program has to be able to run on vanilla CodeBlocks.

like image 872
Josh Avatar asked Feb 17 '23 03:02

Josh


1 Answers

Certainly more compact, if not more elegant solutions are possible, but this does it--

#include <string>

//... read input_str from the file

int pos = input_str.find_first_of(',');
std::string firstname = input_str.substr(pos+1),
      lastname = input_str.substr(0, pos);

std::string output_str = firstname + " " + lastname;
like image 62
Matt Phillips Avatar answered Apr 30 '23 07:04

Matt Phillips