c++输入字符串和子字符串 输出子字符串在字符串中出现的次数 并输出字符串中的字母

很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++输入字符串和子字符串 输出子字符串在字符串中出现的次数 并输出字符串中的字母)