【问题标题】:how to add a number to each character of a string如何将数字添加到字符串的每个字符
【发布时间】:2015-04-29 17:56:12
【问题描述】:

我必须在 C 中编写一个函数,该函数接收一串字符,然后将数字 13 添加到每个字符。我想出了这个解决方案:

#include<stdio.h>

main() 
{
     char text[100];
     gets(text);
     code (text);
     }

 code (char text[100])
{
    int i;
    for(i=0;i<=98;i++)
    {
        text[i]=text[i] + 13 ;
    }
    printf ("%s",text);
    return (0);

}

是这样吗?

【问题讨论】:

  • 这样对吗?你测试了吗?如果它有效,我想没关系。
  • 这个问题更适合codereview.stackexchange.com
  • @reggaeguitar 不,不是。代码审查适用于有效且希望变得更清洁的东西。不是为了“这对吗?” / "这行得通吗?"
  • 很公平,我只是认为该操作会从了解 codereview.stackexchange 中受益,并且可能会获得一些更有帮助的反馈,而不会因为在那里发布而被否决

标签: c string function


【解决方案1】:

你需要看一些细节:

// a void function should NOT return

void code (char text[]){
// when passing a string as argument, you don't need to indicate its' size

    int i = 0; // pay attention to give a value when initializing

    while (text[i] != '\0') { // '\0' indicates string's end...

        // while not the end
        text[i] += 13;    // same as text[i] = text[i] + 13;
        i += 1;           // same as i = i + 1;

    }

    printf("%s", text);
    // the string was encoded
}

例子:

char text[100];  // its' size is 100, but..
gets(text);      // if you read "hello" from input/keyboard

结果将是:

value ->        h  e  l  l  o  \0 
                |  |  |  |  |   |
position ->     0  1  2  3  4   5  ....

您的文本在位置 5.... 结束。因为那样,您需要搜索 '\0',以找到字符串结束的位置..

希望对你有帮助。

【讨论】:

  • 为什么不for ( int i = 0; text[i]; i++ ) text[i] += 13; 甚至for ( int i = 0; text[i]; text[i++] += 13 );
  • @i486...是的,你可以!我不知道...但我在这里尝试过,它有效:ideone.com/QWxaFz 当字符包含 '\0' 时,它返回 false
  • 事实上,"false" 在 C 中是零,而 '\0' 也是零。
【解决方案2】:

code 函数应该有一个返回类型,如果它不需要返回任何东西,请将其类型设置为void
在使用它之前应该存在一个函数原型/定义。
用户不一定要输入一个固定长度的字符串,所以使用string.h头文件中的strlen函数来计算输入字符串的长度。
main()的标准定义应该是如int main(){ return 0;}

#include<stdio.h>
#include<string.h>
void code(char []);
int main()
{
    char text[100];
    gets(text);
    code (text);
    return 0;
}

void code (char text[100])
{
    int i;
    int length=strlen(text);
    for(i=0;i<=length;i++)
    {
        text[i]=text[i] + 13 ;
    }
    printf ("%s",text);
    //return (0);
}

【讨论】:

    猜你喜欢
    • 2021-08-02
    • 1970-01-01
    • 2017-07-14
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    相关资源
    最近更新 更多