如何在C++中拆分字符串

How to split a string in C++

本文关键字:拆分 字符串 C++      更新时间:2023-10-16

我有非常基本的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);