tags:

views:

175

answers:

4

Given a string consisting of a single character followed by a number (one or two digits), I would like to split it into a character and an integer. What is the easiest way to accomplish this?

My thoughts so far:

I can easily grab the character like so:

string mystring = "A10";
char mychar = mystring[0];

The hard part seems to be grabbing the one or two digit number that follows.

+3  A: 

You can make use of the operator[], substr, c_str and atoi as:

string s = "A10";
char c = s[0]; // c is now 'A'
int n = atoi((s.substr(1,2)).c_str()); // n is now 10

EDIT:

The above will also work if s="A1". This is because if the 2nd argument to substr makes the substring to span past the end of the string content, only those characters until the end of the string are used.

codaddict
+13  A: 
#include <sstream>

char c;
int i;    
std::istringstream ss("A10");
ss >> c >> i;//First reads char, then number. Number can have any number of digits. 
             //So your J1 or G7 will work either.
Draco Ater
I haven't tried it, but shouldn't you be able to do ss >> c >> i; ?
Zan Lynx
I'd also use the input operator to grab the char: `std::istringstream ss("A10"); char c; int i; ss >> c >> i;` This method keeps the extraction consistent. (@Zan Lynx beat me to the punch, but I actually tried it first!)
JonM
I haven't either, but it works too. Thanks :)
Draco Ater
+1 for being the answer that actually uses C++ instead of C.
JUST MY correct OPINION
+1  A: 

Using sscanf()

std::string s = "A10";
int i;
char c;
sscanf(s.c_str(), "%c%d", &c, &i);
/* c and i now contain A and 10 */

This is more of a "C way" of doing things, but works none-the-less.

Here is a more "C++ way":

std::string s = "A10";
std::cout << *s.begin() << s.substr(1, s.size()) << std::endl;
/* prints A10 */
Nick Presta