【问题标题】:Append char to string - the NXC language将字符附加到字符串 - NXC 语言
【发布时间】:2013-10-16 20:08:55
【问题描述】:

我想给自己写一个类似于 PHP 的 str_repeat 的函数。我希望这个函数在字符串末尾添加指定数量的字符。

这是一个不起作用的代码 (string argument 2 expected!)

void chrrepeat(const char &ch, string &target, const int &count) {
  for(int i=0; i<count; i++)
    strcat(target, ch);
}

【问题讨论】:

  • 你可以使用连接运算符吗?例如:target = target + ch

标签: string char nxc


【解决方案1】:

我不完全知道那是什么语言(C++?),但您似乎将一个字符传递给strcat(),而不是一个以空字符结尾的字符串。这是一个微妙的区别,但strcat 会很高兴地访问更多无效的内存位置,直到找到一个空字节。

您可以为此创建一个自定义函数,而不是使用效率低下的strcat,因为它必须始终搜索到字符串的末尾。

这是我在 C 中的实现:

void chrrepeat(const char ch, char *target, int repeat) {
    if (repeat == 0) {
        *target = '\0';
        return;
    }
    for (; *target; target++);
    while (repeat--)
        *target++ = ch;
    *target = '\0';
}

根据在线手册,我让它为 repeat == 0 的情况返回一个空字符串,因为这就是它在 PHP 中的工作方式。

此代码假定目标字符串拥有足够的空间来进行重复。该函数的签名应该很容易解释,但这里有一些使用它的示例代码:

int main(void) {
    char test[32] = "Hello, world";
    chrrepeat('!', test, 7);
    printf("%s\n", test);
    return 0;
}

打印出来:

Hello, world!!!!!!!

【讨论】:

  • 这是一种用于 NXT 乐高积木的“Not Exactly C”语言。它有一种奇怪的字符串实现(string 不是char*)。
  • 但请不要删除此答案。它可能会帮助被谷歌重定向到这里的其他人。
  • 当然,我不会删除它。我不能再帮你了,我以前从未听说过这种语言。
【解决方案2】:

将字符转换为字符串。

void chrrepeat(char ch, string &target, const int count) {
  string help = "x"; // x will be replaced
  help[0] = ch;
  for(int i=0; i<count; i++)
    strcat(target, help);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 2012-10-04
    • 1970-01-01
    • 2012-12-05
    • 2013-02-09
    • 2012-01-12
    • 1970-01-01
    相关资源
    最近更新 更多