C++ 中字符串的分割

#include <iostream>
#include <string>
using namespace std;


string* get_input_string(string source){        //将string以空格为分割符分割成字符串数组
    int current_pos = 0;            //字符串数组的索引
    string* arr = new string[source.size()];        //创建字符串数组
    string tmp = "";                    //临时字符串
    for(int i = 0; i < source.size(); i++){             //遍历字符串
        if(source.at(i) == ' ' || i == source.size() - 1){      //如果遇到空格或者是最后一个字符
            arr[current_pos] = tmp;         //将临时字符串赋值给字符串数组
            current_pos++;      //索引加1
            tmp = "";       //清空临时字符串
        }else{              //如果不是空格
            tmp += source.at(i);        //将字符加入临时字符串
            
        }   
    }
    arr[current_pos + 1] = '\0';        //最后一个字符串加上结束符
    return arr;         //返回字符串数组
}

int main(){
    string source = "123 2 333 44 5 6 7 8 9 101";
    string *arr = get_input_string(source);
    cout << "arr: " << arr->length() << endl;
    int i = 0;
    while(arr[i] != "\0"){
        cout << arr[i++] << endl;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++,可以使用一些方法来实现英文字符串分割。以下是一种常见的方法: 1. 使用标准库函数: 可以使用C++标准库字符串处理函数来实现字符串分割,例如使用`std::string`的`find`和`substr`函数。 示例代码如下: ```cpp #include <iostream> #include <string> int main() { std::string str = "Hello, 你好"; std::string delimiter = ", "; size_t pos = 0; std::string token; while ((pos = str.find(delimiter)) != std::string::npos) { token = str.substr(0, pos); std::cout << token << std::endl; str.erase(0, pos + delimiter.length()); } std::cout << str << std::endl; return 0; } ``` 运行结果: ``` Hello 你好 ``` 这个示例代码,我们使用了`find`函数来查找分隔符的位置,然后使用`substr`函数来提取子字符串。通过循环不断提取子字符串,直到没有分隔符为止。 2. 使用第三方库: 除了使用标准库函数,还可以使用一些第三方库来实现字符串分割,例如Boost库的`split`函数。 示例代码如下: ```cpp #include <iostream> #include <string> #include <boost/algorithm/string.hpp> int main() { std::string str = "Hello, 你好"; std::vector<std::string> tokens; boost::split(tokens, str, boost::is_any_of(", ")); for (const auto& token : tokens) { std::cout << token << std::endl; } return 0; } ``` 运行结果: ``` Hello 你好 ``` 这个示例代码,我们使用了Boost库的`split`函数来实现字符串分割。该函数将字符串按照指定的分隔符进行分割,并将结果存储在一个`std::vector`容器

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值