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;

}

相关推荐
晨曦中的暮雨2 小时前
限流算法——固定窗口、滑动窗口、漏桶、令牌桶
java·开发语言·算法
喵了几个咪3 小时前
GoWind CMS 拆解:在 Go 里给 TipTap 搭一套 Yjs 协同后端
开发语言·后端·golang
程序员清风3 小时前
数据处理脚本工程化:日志、配置、命令行与测试
服务器·开发语言·数据库
文丑颜不良啊3 小时前
LeetCode876~900题目解析
java·leetcode
aloha_7894 小时前
Java 基础、集合、异常与 JUnit 5 速查
java·junit·sqlserver
知守观5 小时前
设计模式实战:从真实老项目中看标准模板方法与工厂的落地
java·spring·设计模式
2601_962885725 小时前
如何用 Python 把 K 线重采样成任意周期?
开发语言·python
独隅5 小时前
Claude API 实战教程:从入门到完整项目
android·java·数据库·claude·claude code
choumin5 小时前
C++中万能引用与std::forward的作用和用法
c++·万能引用·std forward
Wang's Blog5 小时前
Java 项目实战: 交友项目 - 圈子功能实现:总结
java·开发语言·交友