字符串重复替换为连字符 C++

string repetition replaced by hyphen c++

本文关键字:连字符 C++ 替换 字符串      更新时间:2023-10-16

我是编码初学者,正在尝试这个问题,用连字符替换字符串中字母的所有重复:即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++11。

#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
std::string f(std::string s)
{
auto first{s.begin()};
const auto last{s.end()};
while (first != last)
{
auto next{first + 1};
if (std::isalpha(static_cast<unsigned char>(*first)))
std::replace(next, last, *first, '-');
first = next;
}
return s;
}
int main()
{
const std::string input{"ABCDBEFKAJHLB"};
std::cout << f(input) << 'n';
return 0;
}

首先,请注意 ASCII 表中的英文大写字母在此范围内 65-90。static_cast<int>('A')转换大写字母将生成一个整数。如果在大小写后数字在 65-90 之间,我们知道它是一个大写字母。对于小写字母,范围为 97-122。否则,该字符基本上不是字母。

选中创建一个数组或布尔向量并跟踪重复的字母。简单的方法是

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string str("ABCDAKEAK");
vector<bool> vec(26,false);
for(int i(0); i < str.size(); ++i){
if(  !vec[static_cast<int>(str[i]) - 65]  ){
cout << str[i];
vec[static_cast<int>(str[i]) - 65] = true;
}else{
cout << "-";
}   
}
cout << endl;
return 0;
}

注意:我假设输入只有字母,它们是大写的。这个想法围绕着通过布尔进行跟踪。

当您假设输入字符编码为 UTF-8 时,您可以像下面这样重构:

#include <iostream>
#include <string>
#include <optional>
#include <utility>
std::optional<std::size_t> char_to_index(char u8char){
if (u8'a' <= u8char && u8char <= u8'z'){
return u8char - u8'a';
}
else if (u8'A' <= u8char && u8char <= u8'A'){
return u8char - u8'A';
}
else {
return std::nullopt;
}
}
std::string repalce_mutiple_occurence(std::string u8input, char u8char)
{
bool already_found[26] = {};
for(char& c : u8input){
if (const auto index = char_to_index(c); index && std::exchange(already_found[*index], true)){
c = u8char;
}
}
return u8input;
}
int main(){
std::string input;
std::getline(std::cin, input);
std::cout << repalce_mutiple_occurence(input, u8'-');
}

https://wandbox.org/permlink/UnVJHWH9UwlgT7KB

注意:在 C++20 上,您应该使用char8_t而不是使用char