C++ 提取字符串中的數字
1 #include <iostream> 2 using namespace std; 3 int main() 4 { 5 char a[50] = "1ab2cd3ef45g"; 6 char b[50]; 7 int cnt_index = 0, cnt_int = 0; 8 //cnt_int 用於存放字符串中的數字. 9 //cnt_index 作為字符串b的下標. 10 11 for (int i = 0; a[i] != '\0'; ++i) //當a數組元素不為結束符時.遍歷字符串a. 12 { 13 if (a[i] >= '0'&& a[i] <= '9') //如果是數字. 14 { 15 cnt_int *= 10;//先乘以10保證先檢測到的數字存在高位,后檢測的存在低位 16 cnt_int += a[i] - '0'; //數字字符的ascii-字符'0'的ascii碼就等於該數字. 17 } 18 19 else if ((a[i] >= 'a'&&a[i] <= 'z') || (a[i] >= 'A'&&a[i] <= 'Z')) //如果是字母. 20 { 21 b[cnt_index++] = a[i]; //如果是字符,則增加到b數組中. 22 } 23 } 24 25 b[cnt_index++] = '\0'; //增加字符串結束符. 26 27 cout << b << endl; //輸出字符串. (abcdefg) 28 cout << cnt_int << endl; //輸出數字.(12345) 29 return 0; 30 }