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

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

#include <iostream>

#include <cstring>

struct WordCount

{

char word32;

int count;

};

int main()

{

char s\[\] = "hello word start begin hello go test hello word";

WordCount wc100; // 最多 100 个不同单词

int wc_size = 0;

char* p = s;

while (*p)

{

//跳过空格

while (*p == ' ')

p++;

//读取一个单词

char token32;

int idx = 0;

while (*p && *p != ' ')

{

tokenidx++ = *p;

p++;

}

tokenidx = '\0';

if (idx == 0) continue; //避免末尾空白

//判断token 是否已经出现

bool found = false;

for (int i = 0; i < wc_size; i++)

{

if (strcmp(wci.word, token) == 0)

{

wci.count++;

found = true;

break;

}

}

//新单词

if (!found)

{

strcpy_s(wcwc_size.word, token);

wcwc_size.count = 1;

wc_size++;

}

}

//输出结果

for (int i = 0; i < wc_size; i++)

{

std::cout << wci.word << ":" << wci.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;

}

相关推荐
benbenAItalk6 小时前
数字人口播视频的批量生产实践:素材规范、任务编排与质量验收
java·前端·音视频
sunshine22 girl6 小时前
Java学习二 基本语法2, 算术运算符
java·学习
2601_966949656 小时前
为什么量化策略需要大量历史股票数据?从回测可信度理解数据规模
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
niucloud-admin7 小时前
JAVA V6 多商户商城 开发文档——插件目录结构
java·开发语言
2601_962885727 小时前
如何用 Python 扫描 A 股跳空缺口并统计缺口回补概率?
java·前端·python
anew___7 小时前
蜂鸣器播放音乐——让 Arduino 唱出旋律
c++·stm32·单片机·嵌入式硬件·c
滕州市燕猫虎计算机科技工作室个体工商户7 小时前
Java锁
java·开发语言
多加点辣也没关系7 小时前
JavaScript|第31章:表单与控件
开发语言·javascript·ecmascript
菜鸟~noob2337 小时前
【电子战】 第09篇:阵列信号处理——波束形成、MVDR、MUSIC【含matlab代码】
开发语言·matlab·信号处理
ocean21038 小时前
2025-2026年Python面试高频知识点洞察
开发语言·python·面试·python八股文