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.
Asked
Active
Viewed 1.2k times
4
-
3You can use `[tagName]` to filter results by tag. There are some good splitting solutions in a question near the top of the FAQ/votes list for C++ as well. – chris Mar 19 '13 at 04:14
-
1http://stackoverflow.com/questions/236129/splitting-a-string-in-c – Adnan Akbar Mar 19 '13 at 04:16
1 Answers
9
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;

Matt Phillips
- 9,465
- 8
- 44
- 75