问题描述:
对于两个字符串,一个长字符串一个短字符串,在长字符串中查找短字符串出现的次数。例如,对于长字符串str_long为”goodgooledfdsgooglessd”,短字符串str_short为”google”,则输出的结果为出现次数为2次,下标为5和14。
使用string对象实现:
#include<iostream>
#include<string>
using namespace std;
void select_string(string str_long, string str_short);
int main()
{
string str_long, str_short;
cout << "Please enter a long string: ";
cin >> str_long;
cout << "Please enter a short string: ";
cin >> str_short;
//string str_long = "goodgoogleabgoogledfg";
//string str_short = "google";
select_string(str_long, str_short);
system("pause");
return 0;
}
#include<iostream>
#include<string>
using namespace std;
void select_string(string str_long, string str_short)
{
const int num_long = str_long.size();
const int num_short = str_short.length();//两种不同计算string长度的方法
int count = 0;
for (int i = 0; i < num_long - num_short; i++)
{
string str_cut = string(str_long, i, num_short);
//cout << str_cut << endl;
if (str_cut == str_short)
{
count++;
cout << "The " << count << "-th appears in position " << i + 1 << endl;
}
}
cout << "The short string appears " << count << " times" << endl;
}
使用数组实现:
#include<iostream>
#include<string>
using namespace std;
int main()
{
char str_long[40];
char str_short[20];
cout << "Please enter a long string: ";
cin >> str_long;
cout << "Please enter a short string: ";
cin >> str_short;
//char str_long[40] = "gooddfgooglebgooglea";
//char str_short[20] = "google";
int num_long = strlen(str_long);
int num_short = strlen(str_short);
//cout << strcmp(str_short, str_short) << endl;
//cout << str_long << endl;
//cout << str_short << endl;
//cout << "The length of long string is " << num_long << ", the length of short string is " << num_short << endl;
int count = 0;
for (int i = 0; i < (num_long - num_short); i++)
{
char str_cut[20];
int j;
for (j = 0; j < num_short; j++)
{
str_cut[j] = str_long[i + j];
}
str_cut[j] = '\0';
//cout << str_cut << endl;
if (!strcmp(str_cut, str_short))
{
count++;
cout << "The " << count << "-th appears in position " << i + 1 << endl;
}
}
cout << "The short string appears " << count << " times" << endl;
system("pause");
return 0;
}