很easy的题目,对字符串的处理,基础题。代码如下,请大神指导,谢谢。
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string str;//原字符串
string substr;//子字符串
int cnt=0; //记录字符串次数
//接收输入字符串
cout<<"please input a string: ";
getline(cin,str);
fflush(stdin);
cout<<"please input a substring: ";
getline(cin,substr);
//计算字符串
string::size_type index=0;
for ( ; index!=str.size(); ++index)
{
string::size_type begin=0;
if (str[index] == substr[begin])
{
for (begin=1; begin!=substr.size(); ++begin)
{
if (str[begin] != substr[begin])
{
break;
}
}
if (begin == substr.size())
{
++cnt;
index+=substr.size()-1;
}
}
}
//输出string中的字母
cout<<"string with alpha: "<<endl;
string::size_type i=0;
for ( ; i!=str.size(); i++)
{
if (isalpha(str[i]))
{
cout<<str[i];
}
}
cout<<endl;
//输出是否有子字符串
if (cnt == 0)
{
cout<<"no substring."<<endl;
}
else
{
cout<<"substring nums: "<<cnt<<endl;
}
return 0;
}
这是一道关于C++处理字符串的基础题目,主要任务是找到字符串中子字符串出现的次数,并输出所有字母。代码已给出,欢迎经验丰富的开发者提供反馈。

2015

被折叠的 条评论
为什么被折叠?



