c语言编写函数,接收一个字符串,将其中所有的大写字母转换成小写字母,其他字符不变。要求不使用任何库函数。
时间: 2025-02-12 20:27:37 浏览: 29
在C语言中,你可以通过ASCII码来实现这个功能。因为大写字母的ASCII码值比对应的小写字母的值小32,所以可以利用这个特性来进行转换。下面是一个简单的示例函数,它接收一个指向字符串的指针,并返回一个新的字符串:
```c
#include <stdio.h>
#include <stdlib.h> // 需要malloc来动态分配内存
char* toLowerCase(char* input) {
if (input == NULL) {
return NULL; // 如果输入为空,直接返回NULL
}
int len = strlen(input); // 获取字符串长度
char* output = (char*)malloc((len + 1) * sizeof(char)); // 动态分配足够空间的内存
if (output == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
for (int i = 0; i < len; i++) {
if (input[i] >= 'A' && input[i] <= 'Z') { // 判断是否为大写字母
output[i] = input[i] + 32; // 转换成小写字母
} else {
output[i] = input[i]; // 其他字符不变
}
}
output[len] = '\0'; // 添加终止符
return output;
}
// 测试函数
int main() {
char str[] = "Hello World!";
char* lowerStr = toLowerCase(str);
printf("Original string: %s\n", str);
printf("Lowercase string: %s\n", lowerStr);
free(lowerStr); // 释放动态分配的内存
return 0;
}
```
注意,上述代码中使用了`malloc()`和`free()`函数,这是因为我们在函数内部创建了一个新的字符串。如果不需要保留原始字符串,可以在主函数中直接替换原字符串。
阅读全文
相关推荐


















