将字符串“A10”拆分为char 'A和int 10

时间:2022-12-09 21:43:39

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 个解决方案

#1


4  

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

可以使用运算符[]、substr、c_str和atoi作为:

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.

如果s="A1"也可以。这是因为,如果substr的第二个参数使子字符串跨越字符串内容的末尾,那么只有这些字符才能使用到字符串的末尾。

#2


17  

#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.

#3


2  

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.

这是一种“C方式”的做事方式,但绝对有效。

Here is a more "C++ way":

这里有一个更“c++”的方法:

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

#1


4  

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

可以使用运算符[]、substr、c_str和atoi作为:

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.

如果s="A1"也可以。这是因为,如果substr的第二个参数使子字符串跨越字符串内容的末尾,那么只有这些字符才能使用到字符串的末尾。

#2


17  

#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.

#3


2  

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.

这是一种“C方式”的做事方式,但绝对有效。

Here is a more "C++ way":

这里有一个更“c++”的方法:

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