连字符替换为连字符c ++

编程入门 行业动态 更新时间:2024-10-24 04:35:54
本文介绍了连字符替换为连字符c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

本文发布于:2023-11-29 13:40:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646539.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!