在leetcode 刷题中经常会遇到一个字符串,以空格,或者“,”、“/”等分开然后使用,但是之前一直疏于整理,在这里记录以分隔符分割字符串的方法, 三种方法对应使用情况不同推荐方法3
int main()
{
int length;
string st = "Enter,the,name,of,an,existing,text,file:";
istringstream stream(st);
int i = 0;
char array[20] = { 0 };
while (stream.get(array, 20, ','))
{
length = stream.tellg();
cout << array << endl;
stream.seekg (length + 1, ios::beg);
}
system("pause");
return 0;
}
int main()
{
char str[] = "Please split this sentence into tokens";
char * p = strtok(str, " ");
cout << p << endl;
while (p != NULL)
{
cout << p << endl;
p = strtok(NULL, " ");
}
return 0;
}
int main()
{
string path = "/home/mao/";
stringstream is(path);
string tmp;
while (getline(is, tmp, '/'))
{
cout << tmp << endl;
}
return 0;
}