如何在条件语句中使用ctype.h库?字符串首字母大写函数调试求助
修复字符串单词首字母大写函数的问题
你的代码核心问题是修改字符时的目标位置错误,另外还有ctype库函数的参数类型需要注意,以下是具体修复方案:
1. 核心错误定位
在cap_string函数的条件分支里,你写了:
*s = toupper(s[i]);
*s等价于s[0],也就是字符串的第一个字符,不管循环到哪个i,你都只在修改字符串的第一个位置,自然看不到其他单词首字母被大写的效果。正确的写法应该是修改当前索引i对应的字符:
s[i] = toupper(s[i]);
2. 次要问题:ctype函数的参数类型
isalpha、isspace、ispunct这些ctype库函数的参数要求是unsigned char类型(或者EOF)。如果你的系统中char是有符号类型,当字符的ASCII值大于127时,会被解析为负数,传入这些函数会触发未定义行为。所以需要把参数强制转换为unsigned char。
修正后的完整代码
#include <stdio.h> #include <ctype.h> /** * *cap_string - Capitalize the first letter of each word in a string * @s: Argument pointer to char * Return: Pointer to s variable */ char *cap_string(char *s) { int i; for (i = 0; s[i] != '\0'; i++) { // 转换参数为unsigned char,避免未定义行为 if (isalpha((unsigned char)s[i]) && (i == 0 || isspace((unsigned char)s[i - 1]) || ispunct((unsigned char)s[i - 1]))) { s[i] = toupper((unsigned char)s[i]); } } return (s); } /** * main - Check the code * Return: Always 0 */ int main(void) { char str[] = "Expect the best. Prepare for the worst. Capitalize on what comes.\nhello world! hello-world 012345\n6hello world\thello world.hello world\n"; char *ptr; ptr = cap_string(str); printf("%s", ptr); printf("%s", str); return (0); }
测试效果
运行修正后的代码,输入字符串中的每个单词首字母(包括空白/标点后的第一个字母)都会被正确大写,比如hello world会变成Hello World,hello-world会变成Hello-World,6hello会变成6Hello等。
内容的提问来源于stack exchange,提问作者Mark Bruye
相关产品推荐
相关产品推荐

