如何在C++中拆分字符串
How to split a string in C++
我有非常基本的C代码,我有一个简单的问题。我在谷歌上搜索了我的问题,但我找不到任何可以帮助我的东西。所以,我的问题是我需要拆分一个字符串并输出两个字符串作为结果。我知道strcpy
但它对我不起作用。
假设我们有一个字符串:
stringOne("http://google.com/logo.jpg C:windowsuserDesktoplogo.jpg");
我想将"http://google.com/logo.jpg"复制到另一个字符串中,
stringTow("http://google.com/logo.jpg");
如果我cout << stringTwo << endl;
它将显示 http://google.com/logo.jpg
并"C:windowsuserDesktoplogo.jpg"
到另一个字符串中,
stringThree("C:windowsuserDesktoplogo.jpg");
对不起,我的英语:)很差
假设你正在谈论C++的std::string
,有多种方法可以做到这一点,例如你可以使用string.find和string.assign。
有关其他方法,请查看 std::string 成员函数。
#include <string>
#include <iostream>
int main(int /*argc*/, const char** /*argv*/)
{
std::string stringOne = "http://google.com/logo.jpg C:\windows\user\Desktop\logo.jpg";
std::string stringTwo = "", stringThree = "";
size_t spacePos = stringOne.find(' ');
if (spacePos != std::string::npos) {
// copy 0-spacePos, i.e. all the chars before the space.
stringTwo.assign(stringOne, 0, spacePos);
// copy everything after the space.
stringThree.assign(stringOne, spacePos + 1, std::string::npos);
}
std::cout << "s1 = "" << stringOne << """ << std::endl;
std::cout << "s2 = "" << stringTwo << """ << std::endl;
std::cout << "s3 = "" << stringThree << """ << std::endl;
}
现场演示在这里:http://ideone.com/t2MEiD
使用这种方式,
char str[] = "http://google.com/logo.jpg C:windows\userDesktoplogo.jpg";
char *string1;
char *string2;
string1 = strtok(str, " ");
printf("%sn",string1);
string2 = strtok(NULL, " ");
printf("%sn",string2);
相关文章:
- 我还可以添加什么来按空格或空格正确拆分C++字符串?
- 通过空行提升拆分字符串
- 如何按多个括号类型拆分字符串,但仍将括号保留在C++?
- 如何根据字符拆分字符串
- 在C++中拆分字符串的最佳做法
- 如何使用两个不同的分隔符拆分字符串
- 基于 C++ 中的多个字符串分隔符拆分字符串
- 拆分字符串输入并查找字符是否有效
- 使用 boost::split 按分隔符的前 N 次匹配来拆分字符串
- 如何在C 中不带有弦乐和strtok的情况下拆分字符串(提取单词)
- 为什么在黑客兰克的许多问题中都会完成拆分字符串
- C++拆分字符串反馈
- C++:按制表符拆分字符串,但包含空格
- 基于其中的数字子字符串拆分字符串
- 按空格拆分字符串并将列输出到不同的数组中
- C++ STL 在逗号处拆分字符串
- 如何根据某些字符拆分字符串?经度纬度
- 如何在 c++ 中拆分字符串的一部分
- 如何通过分隔符拆分字符串并将每个字符串放入不同的向量中
- 我如何在QT中的更多子字中拆分字符串