如果前一个字符相同,则跳过数组中的一个字符
skipping a character in an array if previous character is the same
我正在遍历一个chars
数组来进行一些操作。如果有两个相邻的字符相同,我想"跳过"一个迭代。
例如x112abbca
跳过-------^
我有一些代码,但它并不优雅,我想知道是否有人能想出更好的方法?我在switch
语句中有一些case
,如果我不必在switch
中使用if
语句,我会很高兴。
switch(ent->d_name[i])
{
if(i > 0 && ent->d_name[i] == ent->d_name[i-1])
continue;
case ' ' :
...//code omited
case '-' :
...
}
顺便说一句,一位讲师曾经告诉我"除非需要很多代码来替换continue
,否则不要使用它们"。有人支持吗?(实际上他对break
s也是这么说的)
将if
置于switch
之外。
虽然我不反对使用continue
和break
,但这次您当然可以绕过它们,而不需要太多代码:只需恢复条件并将整个switch语句放入if块中。
回答纠正后的问题:什么是干净的取决于许多因素。这个字符列表需要考虑多长时间:你应该自己迭代它们,或者使用<algorithm>
中的实用函数?在任何情况下,如果你多次引用同一个字符,也许你应该给它一个别名:
std::string interesting_chars("-_;,.abc");
// ...
for (i...) {
char cur = abc->def[i];
if (cur != prev || interesting_chars.find(cur) == std::string::npos)
switch (current) // ...
char chr = ' ';
char *cur = &ent->d_name[0];
while (*cur != ' ') {
if (chr != *cur) {
switch(...) {
}
}
chr = *cur++;
}
如果您可以清除正在分析的数组的内容,则可以使用std::unique()
:对其进行预处理
ent->erase(std::unique(ent->d_name.begin(), ent->d_name.end()), ent.end());
这应该用一个副本替换所有相同字符的序列,并适当缩短字符串。如果你不能破解字符串本身,你可以创建一个只有一个字符串的字符序列的副本:
std::string tmp;
std::unique_copy(ent->d_name.begin(), ent->d_name.end(), std::back_inserter(tmp));
如果您使用的是C字符串:请改用std::string
。如果你坚持使用C字符串,并且不想玩std::unique()
,那么比你的方法更好的方法是使用previous
字符,初始化为0
(毕竟这不能是C字符串的一部分):
char previous(0);
for (size_t i(0); ent->d_name[i]; ++i) {
if (ent->d_name[i] != previous) {
switch (previous = ent->d_name[i]) {
...
}
}
}
我希望我能理解你想做什么,无论如何,这会找到匹配的对,并跳过一个匹配。
char c_anotherValue[] = "Hello World!";
int i_len = strlen(c_anotherValue);
for(int i = 0; i < i_len-1;i++)
{
if(c_anotherValue[i] == c_anotherValue[i+1])
{
printf("%c%c",c_anotherValue[i],c_anotherValue[i+1]);
i++;//this will force the loop to skip
}
}
相关文章:
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 使用动态分配将 char* 复制到另一个字符**
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 如何检查一个字符是否与字符数组中的另一个字符匹配?
- C++:使用另一个字符将一个字符大写
- 我可以得到一个字符 * 到一个 std::sregex_iterator 匹配 str() 吗?
- 使用连续分隔符和空最后一个字符进行拆分
- 如何比较文件中包含的下一个字符
- 如何检查字符串中的最后一个字符是否是某个字符并将其从字符串中删除?(C++)
- 如何从文本文件中一次读取一个字符
- 将一个字符替换为字符串中更多数量的字符,而不删除C++中的其他字母
- 读取输入后,输出丢失了一个字符
- 比较最后一个字符,不区分大小写(带谓词?
- 如果一个字符,比如说"9",我减去"0",我在结果上使用 is 数字,我是真还是假
- 为什么 std::istream::gcount 返回的字符比预期的多一个字符
- 使用 fstream 在空格分隔文件中查看下一项(不仅仅是一个字符)的方法
- 使用 char 将一个字符数组分配给另一个字符数组时出现奇怪的行为
- 在弦乐器中删除最后一个字符