c++
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
// 逗号分隔开的串,使用getline()函数
string str("1,2,-3,-4");
string tmp;
int a;
stringstream input(str);
while(getline(input, tmp, ','))
{
a = stoi(tmp); // c++
a = atoi(tmp.c_str()); // c函数
cout << a << endl;
}
// 空格分隔的串,直接流输入即可
string str2 = "1 2 3 -4";
stringstream inpu2(str2);
while(inpu2 >> a)
{
cout << a << endl;
}
return 0;
}
c
- c使用strtok(), sscanf()两个库函数实现
- 头文件分别string.h, stdio.h
- sscanf()函数可以定义format的格式,其中匹配各种括号之类的要求,很方便。
#include <string.h>
#include <stdio.h>
int main()
{
char str[1000010] = "[1,-1];[-2,1];[3,4]";
// scanf("%s", str);
strcat(str, ";");
char *token;
int x, y;
token = strtok(str, ";");
while(token != NULL) {
sscanf(token, "[%d,%d]", &x, &y);
printf("%d %d \n", x, y);
token = strtok(NULL, ";");
}
return 0;
}