如果前一个字符相同,则跳过数组中的一个字符

skipping a character in an array if previous character is the same

本文关键字:一个 字符 数组 如果      更新时间:2023-10-16

我正在遍历一个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之外。

虽然我不反对使用continuebreak,但这次您当然可以绕过它们,而不需要太多代码:只需恢复条件并将整个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
    }
}
相关文章: