gpt4 book ai didi

c++ - 字符串重复由连字符c++替换

转载 作者:行者123 更新时间:2023-11-30 03:14:15 26 4
gpt4 key购买 nike

我是编码初学者,正在尝试这个问题,用连字符替换字符串中所有重复的字母:即 ABCDAKEA 将变为 ABCD-KE-。我使用了开关循环并且它有效,但我想要使其更短,并可能使用递归使其更有效。有任何想法吗?

    #include<iostream>
#include<string.h>
using namespace std;
int main()
{
char x[100];
int count[26]={0}; //initialised to zero
cout<<"Enter string: ";
cin>>x;
for(int i=0; i<strlen(x); i++)
{
switch(x[i])
{
case 'a':
{
if((count[0]++)>1)
x[i]='-';
}
case 'b':
{
if((count[1]++)>1)
x[i]='-';
}
case 'c':
{
if((count[2]++)>1)
x[i]='-';
}
//....and so on for all alphabets, ik not the cutest//
}
}

最佳答案

遍历数组跳过空格,把你以前从未遇到过的字符放在 std::set 中,如果你再次找到它们,你把它们放在重复的 std::set 中 如果您想跟踪有多少重复项,否则将该位置的原始字符串的值更改为连字符。

#include <iostream> 
#include <string>
#include <cctype>
#include <set>

int main() {
std::string s("Hello world");
std::set<char> characters;
std::set<char> duplicates;

for (std::string::size_type pos = 0; pos < s.size(); pos++) {
char c = s[pos];

// std::isspace() accepts an int, so cast c to an int
if (!std::isspace(static_cast<int>(c))) {
if (characters.count(c) == 0) {
characters.insert(c);
} else {
duplicates.insert(c);
s[pos] = '-';
}
}
}

return 0;
}

关于c++ - 字符串重复由连字符c++替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58003555/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com