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;

}

相关推荐
代码游侠1 分钟前
学习笔记——ESP8266 WiFi模块
服务器·c语言·开发语言·数据结构·算法
行者966 分钟前
Flutter跨平台开发适配OpenHarmony:进度条组件的深度实践
开发语言·前端·flutter·harmonyos·鸿蒙
rgeshfgreh9 分钟前
Spring Bean管理机制深度解析
java·spring boot·spring
ling-4510 分钟前
ssm-day07 springboot3、Mybatis-Plus、springboot实战
java·spring boot·后端
DYS_房东的猫11 分钟前
《 C++ 零基础入门教程》第3章:结构体与类 —— 用面向对象组织代码
开发语言·c++
向量引擎13 分钟前
复刻“疯狂的鸽子”?用Python调用Sora2与Gemini-3-Pro实现全自动热点视频流水线(附源码解析)
开发语言·人工智能·python·gpt·ai·ai编程·api调用
少许极端15 分钟前
算法奇妙屋(二十三)-完全背包问题(动态规划)
java·算法·动态规划·完全背包
郑泰科技17 分钟前
快速地图匹配(FMM)的开源工具与代码示例
c++·windows·python·交通物流
CoderCodingNo17 分钟前
【GESP】C++五级练习(贪心思想考点) luogu-P1115 最大子段和
开发语言·c++·算法
Q741_14717 分钟前
C++ 队列 宽度优先搜索 BFS 力扣 429. N 叉树的层序遍历 每日一题
c++·算法·leetcode·bfs·宽度优先