这是为了学校,所以我要求提示,如果可能的话,不要公开的答案。
我需要使用短语“我的名字,当前社区学院”并输出“当前社区学院”,我已经有了一个循环来利用当前社区学院的资本。
至此,我基本上可以掌握以下内容:
#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string phrase = "My Name current community college";
cout << phrase << endl << endl;
for (int i = 0; i < phrase.length(); i++)
{
if (phrase[i] == ' ')
{
phrase[i + 1] = toupper(phrase[i + 1]);
}
}
return 0;
}
我已经尝试过使用str.find和str.erase,但是它们似乎受到限制,因为它们只能搜索单个字符。有没有一种方法可以搜索“当前”(这是我的社区学院的名称)并仅删除字符串中该单词出现之前的所有内容?
更新:感谢Sam我是我能够完成我的任务,这是我现在拥有的:
#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string phrase = "My Name current community college";
cout << phrase << endl << endl;
for (int i = 0; i < phrase.length(); i++)
{
if (phrase[i] == ' ')
{
phrase[i + 1] = toupper(phrase[i + 1]);
}
}
size_t pos = phrase.find("Current");
string output = phrase.substr(pos);
cout << output << endl << endl;
system("PAUSE");
return 0;
}
但是我很着迷,仅仅获得A并不能实现我的目标。是否有一种无需创建新字符串即可完成此任务的方法,例如,保留我的单个字符串,但删除“当前”之前的所有内容。
我知道了,我什至根本不需要子字符串。您可以使用str.find()
结合使用str.erase()
来擦除所有内容,直到使用size_t pos
:
#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string phrase = "My Name current community college";
cout << phrase << endl << endl;
for (int i = 0; i < phrase.length(); i++)
{
if (phrase[i] == ' ')
{
phrase[i + 1] = toupper(phrase[i + 1]);
}
}
size_t pos = phrase.find("Current"); //find location of word
phrase.erase(0,pos); //delete everything prior to location found
cout << phrase << endl << endl;
system("PAUSE");
return 0;
}
您也可以更换
size_t pos = phrase.find("Current");
phrase.erase(0,pos);
与公正phrase = phrase.substr(phrase.find("Current"));
,这也适用。
您可以使用find
查找要开始的索引,也可以使用substr
选择要返回的部分。
size_t position = str.find("Current");
string newString = phrase.substr(position); // get from position to the end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句