Split string "A10" into char 'A' and int 10
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 =开发者_如何学C "A10";
char mychar = mystring[0];
The hard part seems to be grabbing the one or two digit number that follows.
#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.
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.
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 */
精彩评论