在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;
}

本文介绍了在C++中使用三种不同的方法来分割字符串,包括使用istringstream、strtok和stringstream结合getline,每种方法都有其适用场景,对于处理以特定字符为分隔符的字符串提供了实用的代码示例。
2470

被折叠的 条评论
为什么被折叠?



