如何在C中将常量字符指针转换为小写? [英] How to convert constant char pointer to lower case in C?

查看:40
本文介绍了如何在C中将常量字符指针转换为小写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接收 const char* 的函数,我想将其转换为小写.但我收到错误:

I've a function which receives a const char* and I want to convert it to lowercase. But I get the error:

error: array initializer must be an initializer list or string literal

我尝试将字符串变量复制到另一个数组,以便我可以将其小写.但我想我有些困惑.

I tried to copy the string variable to another array so that I could lower case it. But I think I've got something confused.

这是我的功能:

int convert(const char* string)
{
    char temp[] = string;
    temp        = tolower(temp); //error is here
    //do stuff
}

我很难理解这个错误是什么意思,有人可以帮忙解释一下吗?

I'm struggling to understand what this error means, could someone help in explaining it?

推荐答案

tolower 接受单个字符并以小写形式返回.

tolower takes a single character and returns it in lowercase.

即使没有,数组也不能赋值.数组和指针不是一回事.

Even if it didn't, arrays aren't assignable. Arrays and pointers are not the same thing.

您大概想要执行以下操作:

You presumably want to do something like:

char *temp = strdup(string); // make a copy

// adjust copy to lowercase
unsigned char *tptr = (unsigned char *)temp;
while(*tptr) {
    *tptr = tolower(*tptr);
    tptr++;
}

// do things

// release copy
free(temp);

确保您了解堆和堆栈之间的区别,以及影响字符串文字的规则.

Make sure you understand the difference between the heap and the stack, and the rules affecting string literals.

这篇关于如何在C中将常量字符指针转换为小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆