C++ 分别利用数组和string对象实现从长字符串中计算短字符串出现的次数

问题描述:
对于两个字符串,一个长字符串一个短字符串,在长字符串中查找短字符串出现的次数。例如,对于长字符串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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值