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;

}

相关推荐
不吃土豆的马铃薯3 分钟前
Socket 网络编程实战教程
linux·服务器·开发语言·网络·c++·算法
零号全栈寒江独钓9 分钟前
c++跨平台实现日志重定向
linux·c++·windows
搬石头的马农11 分钟前
Claude Code SpringBoot开发:从0到1搭建企业级项目的6个核心Skill
java·人工智能·spring boot·后端·ai编程
西安邮电大学11 分钟前
Redis为什么快?
java·redis·后端·其他·面试
小成2023032026519 分钟前
从C到C++
开发语言·c++
折哥的程序人生 · 物流技术专研20 分钟前
《Java 100 天进阶之路》第39篇:Java泛型方法的定义和使用
java·开发语言·后端·面试·求职招聘
天天进步201521 分钟前
Tunnelto 源码解析 #1:从 tunnelto --port 8000 看内网穿透的完整链路
开发语言
土狗TuGou28 分钟前
SQL内功笔记 · 第6篇:窗口函数的使用ROW_NUMBER等
java·数据库·后端·sql·mysql
啄缘之间28 分钟前
8.【学习】工业级详细接口约束&覆盖率
开发语言·笔记·学习·uvm·sv
Chase_______30 分钟前
【Java基础核心知识点全解·09】Java 内存布局与垃圾回收详解:栈、堆、栈帧、GC Roots 与对象回收
java·开发语言