如果我有所的字符串 .....ZZ..ZZ......Z.1.Z.23Z.4.Z55,

是有一个简单的方法的转变所有 Z字符串中的一个空间,目前的位置?

一些额外的测试串的是:

  • .Z
  • Z.
  • ZZ.
  • .ZZ
  • Z
  • ZZ
  • ZZZ

我想一些更高的投票回答这个问题(包括目前接受一)不工作,在这些测试。

有帮助吗?

解决方案

只是迭代通过的文本和交换字:

int main ()
{
    char text[] = "...Z.Z.Z...", temp;
    int text_len = strlen (text), i;
    for (i = text_len - 1; i >= 0; i--)
    {
        if (text[i] == 'Z')
        {
                temp = text[i+1];
                text[i+1] = text[i];
                text[i] = temp;
        }
    }
    printf ("%s\n", text);
    return 0;
}

生产:

[~]$ gcc zshift.c && ./a.out
....Z.Z.Z..

有很多的讨论在评论关于可能关闭的1错误在上述码。但是,简单的测试/逐步通过就足以显示,这个不是这种情况。

zshift "Z." -> ".Z"
zshift ".Z" -> "."
zshift "Z" -> ""

我认为该行为"放弃"后Zs时移断串是明智的。毕竟,如果你移位整数,位,最终外部界限的整数都下降了。

如果另一个行为是所希望的--例如,转移只字符串中--改变的算法是最少的:

temp = text[i+1];
if (temp == 0) continue;
text[i+1] = text[i];
text[i] = temp;

其他提示

建立在以前发布的码在这里。功能得到str和strlen将复盖str.工作也与后续Z。前进的速度改善,随后Z。

void move_z_right (char* str, int strlen) {
    for (unsigned int i = 0; i < strlen - 1; ++i)
    {
        if (str[i] == 'Z')
        {
            unsigned int j = i+1;
            while (str[j] == 'Z' && j < strlen - 1) ++j;
            if (j == strlen) break; // we are at the end, done
            char tmp = str[j];
            str[j] = str[i];
            str[i] = tmp;
            i = j; // continue after new Z next run
        }
    }
}

注意约翰*米利金的方案是更好的阅读和也正确的。

轻微的修复到先前的答复(移的权利和承担'.'手段",可以移动到这里"):

  char text[] = "...Z.Z.Z...";

  for (int i = strlen(text) - 2); i > 0; --i) {
    if (text[i] == 'Z' && text[i + 1] == '.') {
      text[i] = '.';
      text[i + 1] = 'Z';
    }
  }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top