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;

}

相关推荐
一个天蝎座 白勺 程序猿7 分钟前
AI 学习者的编程技能:Python 高级特性详解(装饰器、生成器、魔法方法实战)
开发语言·人工智能·python·ai编程
饮水桶_T18 分钟前
DUNE:基于依赖图传播的Agent派生记忆一致性更新机制 笔记
开发语言·笔记·算法·电脑
IT研究室29 分钟前
最新计算机毕业设计选题推荐-基于spring boot的家庭医生管理系统-网站-文档指导-Java-springboot
java·spring boot·课程设计
Code_Solitude33 分钟前
c语言:期末复习(7)
c语言·开发语言·算法
潇湘散客40 分钟前
PlantAis插件更新:RVM负实体开关;VUE文件读取与导出等
c++·qt·opengl
金榜题名萱44 分钟前
蓝桥杯 - 旗帜
c语言·数据结构·c++·算法·蓝桥杯
DataMover智迁1 小时前
免费数据库同步工具怎么选?DataMover 的定时全量、增量与 CDC
java·数据库·oracle
程序猿追1 小时前
返库看板最小化后还会刷新吗?HarmonyOS 7 窗口状态实测
android·开发语言·kotlin·harmonyos
Rain的Java大神之路1 小时前
钱扣了,消息却没了:RocketMQ 5.x 事务回查状态到底该放哪?
java·后端·rocketmq
俊俊几年的1 小时前
RK3588 硬件架构详解:CPU、GPU、NPU 与 RKNN 软件栈
linux·c++·python·yolo·numpy·rockchip