繁体   English   中英

C - 将字符数组转换为小写

[英]C - Converting array of char into lower case

目前我有网站存储在 char *banned[100] 中,我想使用以下方法将它们全部转换为小写:

char *banned[100];
int x = 0;
if(fgets(temp, 100, file) != NULL) {
        char *tempstore;
        tempstore = (char*) malloc(sizeof(temp));
        strcpy(tempstore, temp);
        banned[x] = tempstore;
        x++;
    }
char temps[100];        
while(banned[c]){
        temps[c]=putchar(tolower(*banned[c]));
        c++;
}

但结果并不是我所期望的。 我能得到一些关于我做错了什么的提示/提示吗?

由于您知道字符串(字符数组)的大小,因此您可以只使用for循环。

char temps[100];
size_t i;

for(i = 0; i < 100; i++)
  temps[i] = tolower(temps[i]);

使用下面的代码来满足您的要求,

char *strtolower(char *s)
{
    char *d = (char *)malloc(strlen(s));
    while (*s)
    {
        *d =tolower(*s);
        d++;
        s++;
    }
    return d;
}

int main(void)
{
    char *banned[100];
    char *temps[100];
    char temp[100];

    FILE *file = fopen("test.txt", "r");
    int x = 0;

    if (file != NULL)
    {
        while(fgets(temp, 100, file) != NULL)
        {
            char *tempstore;
            tempstore = (char *) malloc(sizeof(temp));
            strcpy(tempstore, temp);
            banned[x] = tempstore;
            x++;

            puts(tempstore);

        }

        int c = 0;

        while(c < x)
        {
            temps[c] = strtolower(banned[c]);
            puts(temps[c]);
            c++;
        }
    }
    return 0;
}

你可以试试这个:

char temps[100];
size_t i;

for(i = 0; temps[i] != '\0'; i++)
  temps[i] = tolower(temps[i]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM