首页 > 解决方案 > 如何分隔具有重复字符的字符串

问题描述

我正在尝试拆分字符串。例如,如果我输入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;

哪里出错了?

标签: c++stringsplitc++14

解决方案


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

#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;
}

推荐阅读