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;

}

相关推荐
编程修仙13 小时前
第九篇 Spring中的代理思想
java·后端·spring
杀死那个蝈坦13 小时前
MyBatis-Plus 使用指南
java·kafka·tomcat·mybatis—plus
liulilittle13 小时前
C++ 并发双阶段队列设计原理与实现
linux·开发语言·c++·windows·算法·线程·并发
I'm Jie13 小时前
告别重复编码!SpringBoot 字段变更(新旧值)日志工具类的规范化设计与优雅实现
java·spring boot·后端
哥谭居民000114 小时前
需求分析,领域划分到选择套用业务模式到转化落地,两个基本案例
java·大数据·需求分析
森G14 小时前
五、Linux字符设备驱动
linux·arm开发·c++·ubuntu
Tao____14 小时前
适合中小型项目的物联网平台
java·物联网·mqtt·开源·iot
小马爱打代码14 小时前
Spring AI:多模态 AI 大模型
java·人工智能·spring
lly20240614 小时前
并查集快速查找
开发语言
李贺梖梖14 小时前
day07 方法、面向对象1
java