我是编码的初学者,正在尝试用连字符替换字符串中字母的所有重复的问题:即ABCDAKEA将变为ABCD-KE-.我使用了switch循环,它可以工作,但是我想要使其更短,并可能使用递归使其更有效.有任何想法吗?
I am a beginner at coding, and was trying this question that replaces all repetitions of a letter in a string with a hyphen: i.e ABCDAKEA will become ABCD-KE-.I used the switch loop and it works, but i want to make it shorter and maybe use recursion to make it more effective. Any ideas?
#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// } }推荐答案
首先,请注意ASCII表中的英文大写字母在65-90的范围内.强制转换为大写字母static_cast<int>('A')将产生一个整数.如果大小写在65-90之间,我们知道这是一个大写字母.对于小写字母,范围是97-122.否则字符基本上不是字母.
First, notice English capital letters in ASCII table fall in this range 65-90. Casting a capital letter static_cast<int>('A') will yield an integer. If after casing the number is between 65-90, we know it is a capital letter. For small letters, the range is 97-122. Otherwise the character is not a letter basically.
选中创建布尔数组或向量并跟踪重复字母.简单的方法是
Check create an array or a vector of bool and track the repetitive letters. Simple approach is
#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; }注意:我假设输入仅是字母,并且它们是大写字母.这个想法围绕通过布尔跟踪.
Note: I assume the input solely letters and they are capital. The idea is centered around tracking via bool.
更多推荐
连字符替换为连字符c ++
发布评论