如何将一个字符串切成另一个字符串

how to cut a string into another string

本文关键字:字符串 一个 另一个      更新时间:2023-10-16

用户应该输入类似这个字符串的内容"[1 -2.5 3;4 5.25 6;7 8 9.12]"

我想把它剪成只有其中的数字,所以它看起来像这样 1 -2.5 3 4 5.25 6 7 8 9.12

好吧,我已经尝试了下面的代码,但它似乎不起作用

    string cutter(string s){
        string cuttedstring="";
        string fullstring="";
        for(int i=0; i <= s.length(); i++ ){
            if(s.at(i)!= "[" && s.at(i)!= "]" && s.at(i)!= ";"){
                for(int j=i; j<15 ; j++ ){
                    do{
                        cuttedstring += s.at(j);
                     }
                    while(s.at(j)!= " ");
                    fullstring = cuttedstring + " " ;
                    cuttedstring = "";
                }
            }
        }
        return fullstring;
    }

你可以像这样使用字符串类的替换方法:

#include <algorithm>
#include <string>
int main() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y');
}

但是,如果要替换多个字符,则可以使用此方法。

std::string ReplaceAll(std::string str, const std::string& from, const std::string& to) {
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
    }
    return str;
}

如果在此页面上找到它。

相关文章: