用go写一个计算重复字符的函数
时间: 2023-03-24 18:01:23 浏览: 74
好的,以下是一个使用 Go 编写的计算重复字符的函数:
```
func countDuplicateChars(s string) int {
charCount := make(map[rune]int)
duplicates := 0
for _, char := range s {
charCount[char]++
if charCount[char] == 2 {
duplicates++
}
}
return duplicates
}
```
该函数接受一个字符串参数 `s`,并使用一个 `map` 来记录每个字符出现的次数。然后,遍历字符串中的每个字符,每次遇到一个字符,就将该字符在 `map` 中的计数加 1。如果计数达到 2,则将 `duplicates` 计数器加 1。最后返回重复字符的数量。
相关问题
用go写一个去除吃饭字符的函数
好的,以下是一个使用 Go 语言编写的函数,用于去除字符串中的食物字符:
```
func removeFoodChars(s string) string {
foodChars := []string{"米饭", "面条", "牛肉", "鸡肉", "鱼肉"}
for _, char := range foodChars {
s = strings.ReplaceAll(s, char, "")
}
return s
}
```
在这个函数中,我们定义了一个字符串切片 `foodChars`,其中包含了需要删除的食物字符。然后,我们使用 `strings.ReplaceAll` 函数将字符串 `s` 中出现的食物字符都替换为空字符串。最后,我们返回修改后的字符串 `s`。
注意,这个函数只会删除完整的食物字符,而不会删除包含食物字符的单词或子串。如果需要更精确的匹配,可以使用正则表达式等高级技巧来实现。
用c++20标准写一个函数计算字符串中的单词数
好的,以下是用C 20标准写一个函数计算字符串中单词数的代码:
```c
#include <stdio.h>
#include <ctype.h>
int countWords(char *str) {
int count = 0;
int inWord = 0;
while(*str) {
if(isspace(*str)) {
inWord = 0;
} else if(!inWord) {
inWord = 1;
count++;
}
str++;
}
return count;
}
int main() {
char str[] = "This is a test string.";
printf("Number of words: %d", countWords(str));
return 0;
}
```
请确认是否收到我的回答,还需要我帮你做什么?