C++_面试题_21_字符串操作

1. 统计字符串出现的次数

#include <iostream>
#include <cstring>


struct WordCount
{
    char word[32];
    int count;
};

int main()
{
    char s[] = "hello word start begin hello go test hello word";
    WordCount wc[100];     // 最多 100 个不同单词
    int wc_size = 0;

    char* p = s;

    while (*p)
    {
        //跳过空格
        while (*p == ' ')
            p++;
        //读取一个单词
        char token[32];
        int idx = 0;

        while (*p && *p != ' ')
        {
            token[idx++] = *p;
            p++;
        }
        token[idx] = '\0';
        if (idx == 0) continue;  //避免末尾空白


        //判断token 是否已经出现
        bool found = false;

        for (int i = 0; i < wc_size; i++)
        {
            if (strcmp(wc[i].word, token) == 0)
            {
                wc[i].count++;
                found = true;
                break;
            }
        }

        //新单词
        if (!found)
        {
            strcpy_s(wc[wc_size].word, token);
            wc[wc_size].count = 1;
            wc_size++;
        }
    }

    //输出结果
    for (int i = 0; i < wc_size; i++)
    {
        std::cout << wc[i].word << ":" << wc[i].count << std::endl;
    }

    return 0;
}
 

#include <iostream>
#include <string>
using namespace std;
std::string replaceSpaces(const std::string& input,
    const std::string& replacement) {
    std::string output;
    for (char c : input) {
        if (c == ' ') {
            output += replacement;
        }
        else
        {
            output += c;
        }
    }
    return output;
}

int main()
{
    std::string input = "Hello World! Welcome to C++  programming.";
    std::string replaced = replaceSpaces(input, "%20");
    std::cout << "Original string: " << input <<
        std::endl;
    std::cout << "Replaced string: " << replaced <<
        std::endl;
    return 0;
}

     

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值