Divide the string "A10" by char 'A' and int 10

For a string consisting of one 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 do this?

My thoughts so far are:

I can easily capture a character like this:

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

The hard part seems to capture a one-two-digit number.

+3
source share
3 answers

You can use 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:

, s="A1". , 2nd substr , .

+4
#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.
+17

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 like a "C-way", but nothing works.

Here is a more "C ++ path":

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

Source: https://habr.com/ru/post/1743449/


All Articles