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;

}

相关推荐
Lxinccode2 小时前
docker(25) : 银河麒麟 V10离线安装docker
java·docker·eureka·银河麒麟安装docker·银河麒麟安装compose
遇见火星2 小时前
LINUX的 jq命令行处理json字段指南
java·linux·json·jq
Dream it possible!3 小时前
LeetCode 面试经典 150_二叉树_二叉树展开为链表(74_114_C++_中等)
c++·leetcode·链表·面试·二叉树
yi碗汤园3 小时前
【一文了解】C#反射
开发语言·unity·c#
高山上有一只小老虎3 小时前
等差数列前n项的和
java·算法
rockmelodies3 小时前
东方通安装
java
小羊失眠啦.3 小时前
用 Rust 实现高性能并发下载器:从原理到实战
开发语言·后端·rust
避避风港3 小时前
Java 抽象类
java·开发语言·python
初学小白...3 小时前
JVM入门知识点
java·服务器·jvm