【问题标题】:How do I append character gotten from loop to a string and return the value of the string as my output如何将从循环中获取的字符附加到字符串并将字符串的值作为输出返回
【发布时间】:2022-11-30 05:12:41
【问题描述】:

在用 C 语言(不使用 printf 或 putchar)将每个字符设为大写后,我想将字符作为单个字符串返回。目的是在添加每个字符后返回字符串的值

#include <stdio.h>
#include <string.h>

char *my_upcase(char *param_1)
{
    int j = 0;
    char *result = "";
    char *str;
    
    while (j < strlen(param_1))
    {
        char toupper = param_1[j];
        if(toupper >= 'a'){
            // putchar(toupper - 32);
            *str = toupper - 32;
            strncat(result, &toupper -32, 1);
            putchar(*str);
        }else {
        // putchar(toupper);
        *str = toupper;
         strncat(result, &toupper, 1);
         putchar(*str);
        }
        j++;
    }
    return result;
}

【问题讨论】:

    标签: c char c-strings uppercase function-definition


    【解决方案1】:

    函数实现没有意义。

    首先,如果函数不改变源字符串,那么它的参数应该用限定符 const 声明

    char * my_upcase( const char *param_1 );
    

    本声明

    char *result = "";
    

    声明一个指向字符串的指针;迭代。您不能更改字符串文字。任何更改字符串文字的尝试都会导致未定义的行为。

    本声明

    char *str;
    

    声明一个具有不确定值的未初始​​化指针。取消引用此类指针会导致未定义的行为。

    您需要动态分配一个字符数组并将转换为大写的源字符串的字符复制到其中。

    使用函数strncat 是低效的。

    并且不要使用像 32 这样的幻数。而是使用标头 &lt;ctype.h&gt; 中声明的标准 C 函数 toupper

    例如,可以通过以下方式定义函数

    #include <string.h>
    #include <ctype.h>
    
    //...
    
    char * my_upcase( const char *param_1 )
    {
        char *result = malloc( strlen( param_1 ) + 1 );
    
        if ( result != NULL )
        {
            char *p = result;
    
            while ( ( *p = toupper( ( unsigned char )*param_1 ) ) != '
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 2012-01-12
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 2022-01-13
    • 1970-01-01
    相关资源
    最近更新 更多