【问题标题】:Tolower function for array of strings in CC中字符串数组的Tolower函数
【发布时间】:2015-06-21 01:32:03
【问题描述】:

我有一个字符串数组,我正在尝试将所有字符转换为小写。

void make_lower(char **array)
{   
int i = 0;
while (array[i] != NULL){
       array[i] = tolower(array[i]);
       i++;
}
}

我知道 tolower 函数一次读取一个字符,而不是一次读取整个字符串。这就是为什么我认为我必须使用这样的循环,但我仍然收到警告并且该功能不起作用:

passing argument 1 of ‘tolower’ makes integer from pointer without
a cast [-Werror]
note: expected ‘int’ but argument is of type ‘char *’
assignment makes pointer from integer without a cast [-Werror]

非常感谢您的帮助。

【问题讨论】:

  • 使用双循环。一个迭代字符串的数量,另一个迭代每个字符串中的每个字符。 array 的类型为 char**tolower 需要 int 类型的参数,但您给出 array[i] 类型为 char*
  • 因为array[i]是字符串,需要再循环一次。
  • 指向指针的指针不是数组。它指向什么,一个指针数组?

标签: c arrays string pointers tolower


【解决方案1】:

您需要一对嵌套循环,一个用于字符串,一个用于其中的字符。

#include <stdio.h>
#include <ctype.h>

void make_lower(char **array)
{   
    int i = 0, j;
    while (array[i] != NULL){
        j = 0;
        while (array[i][j] != '\0') {
             array[i][j] = tolower(array[i][j]);
             j++;
        }
        i++;
    }
}    

int main(void) {
    char s1[]="ONE", s2[]="tWo", s3[]="thREE";
    char *array[] = {s1, s2, s3, NULL };
    make_lower(array);
    printf ("%s\n", array[0]);
    printf ("%s\n", array[1]);
    printf ("%s\n", array[2]);
    return 0;
}

节目输出:

one
two
three

【讨论】:

  • 您可以将列表的大小传递给函数,而不是在字符串列表的末尾有一个 NULL 指针。它可能会稍微加快程序的速度。
猜你喜欢
  • 2011-03-25
  • 1970-01-01
  • 2013-12-17
  • 1970-01-01
  • 2018-06-19
  • 2021-03-28
  • 1970-01-01
  • 2016-01-16
  • 1970-01-01
相关资源
最近更新 更多