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;

}

相关推荐
码客-ygluu6 小时前
X3 LUA 异步分布式微服务集群框架
c++·架构·lua
starzy19907 小时前
深入理解Scala隐式类:扩展方法机制
开发语言·人工智能·scala
Pniubi7 小时前
怎么排查慢SQL,怎么解决?
java·数据库·sql
M--Y7 小时前
LangGraph 工作流模式
开发语言·javascript·python·langchain·大模型·llm·langgraph
薛之谦_8 小时前
Java 全栈知识体系:从 IDEA 高效开发到 JVM、并发与 Stream 实战
java·jvm·intellij-idea
九英里路9 小时前
protobuf快速上手
网络·c++·中间件·json·谷歌·序列化·protobuf
吴可可1239 小时前
WScript Shell操作注册表详解
开发语言
纪念 2299 小时前
C++ 算法基础 (差分)
开发语言·c++·算法
文丑颜不良啊12 小时前
LeetCode2761~2780题目解析
java·leetcode
IT枫斗者枫哥12 小时前
子线程断言失败,JUnit 为什么还显示通过?
java·后端