【问题标题】:How to separate a string with duplicated characters如何分隔具有重复字符的字符串
【发布时间】:2021-04-29 22:23:33
【问题描述】:

我正在尝试拆分字符串。例如,如果我输入Shooby Dooby by the Wooby Sisters,该函数应该拆分字符串,以便结果为

Title: Shooby Dooby
Artist: the Wooby Sisters

但我从我的代码中得到的是

Title: Shoo
Artist: Sisters

我的代码是

string getArtistStr(string fName){
    string retVal = fName;
    if (fName.length() > 0){
        int pos = fName.find_last_of(" by ");
        if (pos != string::npos){
            retVal = fName.substr(pos+1);
        }
    }
    return retVal;
}

string getTitleStr(string fName){
    string retVal = fName;
    int pos = fName.find_first_of(" by ");
    if (pos != string::npos){
        retVal = fName.substr(0,pos);
    }
    return retVal;
}
cout << "Title: " << getTitleStr(fullName) << endl;
cout << "Artist: " << getArtistStr(fullName) << endl << endl;

哪里出错了?

【问题讨论】:

  • 查看.find_last_of 的文档。我认为它会找到最后一次出现的 any 提供的字符。
  • 您确定输入可以正常工作吗?如果您需要我们的帮助,您必须给我们一个minimal reproducible example。否则,您需要自己调试程序(例如,通过使用调试器逐语句逐句执行代码)。
  • 这种retVal 技术会适得其反并且是一个坏习惯。您正在分配,制作一个副本,然后踩踏它,制作 another 副本,然后返回该副本,这将制作另一个副本。最好直接 return 你想要的,比如 return fName.substr(pos+1)return fName 如果其他块没有触发。
  • 既然您花费了所有这些精力来寻找要拆分的目标,为什么不返回一个 std::tuplestd::pair 字符串,以便您可以一次性完成此操作?
  • 你的意思可能是使用find(),就像fName.find(" by ")一样

标签: c++ string split c++14


【解决方案1】:

这里是您的问题的解决方案:

#include <iostream>
#include <string>

using namespace std;

const string DELIMITER = " by ";

string getArtistStr(const string& fName){
    string retVal = fName;
    if (fName.length() > 0){
        // Searches the string for the first occurrence of the delimiter
        int pos = fName.find(DELIMITER);
        if (pos != string::npos){
            // Incrementing the position to read after the occurrence of the delimiter
            retVal = fName.substr(pos+DELIMITER.length());
        }
    }
    return retVal;
}

string getTitleStr(const string& fName){
    string retVal = fName;
    // Searches the string for the first occurrence of the delimiter
    int pos = fName.find(DELIMITER);
    if (pos != string::npos){
        retVal = fName.substr(0,pos);
    }
    return retVal;
}

int main()
{
    string fullName = "Shooby Dooby by the Wooby Sisters";
    cout << "Title: " << getTitleStr(fullName) << endl;
    cout << "Artist: " << getArtistStr(fullName) << endl << endl;
}

【讨论】:

  • 包含工作代码很棒,但bits/stdc++ 是一个真正的问题。它是不可移植的,也是一个不好的习惯。
猜你喜欢
  • 2021-11-10
  • 1970-01-01
  • 2021-01-14
  • 2019-03-10
  • 1970-01-01
  • 2020-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多