c++ - 如何分隔具有重复字符的字符串
问题描述
我正在尝试拆分字符串。例如,如果我输入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;
哪里出错了?
解决方案
这是您的问题的解决方案:
#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;
}
推荐阅读
- c# - 用于方法组中的泛型类型调用的 RealProxy 调用消息中的 TargetException
- google-bigquery - BigQuery ML - Syntax error: Unclosed comment. When creating model
- android - RxJava2- 可完成永无止境
- php - 将 div 生成为 pdf
- php - 用于替换两个搜索字符串的 PHP 内置函数
- angular - Angular(v6)表单中的'无法读取属性'hasError' of null'
- sqlite - 常见的免费 GIS/地理数据库(PostgreSQL/PostGIS、SQLite/SpatiaLite、H2/H2GIS、...)的功能完整性比较
- javascript - 在 ASP.Net Core 中使用 SharedLocalizer 和 javascript
- android - queryIntentActivities() 和 resolveActivity() 有什么区别。哪一种是了解现有应用程序的最佳方法?
- azure-devops - 部署组阶段结束后后台进程终止