C函数大写单词的第一个字母在一个数组 [英] C function to capitalize first letter of words in an array
问题描述
我是pretty新的C和创建以下功能时,我击中墙壁。我想用这个功能,使一个字大写的第一个字母为静态字符数组(字符字符串[],它看起来不错,以我的眼睛,但我发现这是一些语法错误可能是pretty基本。
编译器错误:
错误:从
为const char无效的转换来
为const char *'
初始化的`为size_t strlen的(为const char *)参数1'
只读位置的分配
块引用>无效帽(字符字符串[]){
INT I;
INT X = strlen的(字符串);
对于(i = 1; I< X,我++){
如果(因而isalpha(串[I])及&放大器;串[I-1] ==''){
//单词的只有第一个字母。
字符串[我] = TOUPPER(字符串[我]);
}如果(因而isalpha(字符串[0]))
{
串[0] = TOUPPER(字符串[0]);
}
}
}
解决方案我把你的code,并试图对其进行编译。那么,这将是很高兴看到编译$ C $接下来的时间C。这里有一个带有注释。
的#include<&stdio.h中GT; //现在我可以用printf。
#包括LT&;&string.h中GT; //我无法使用strlen没有这个...无效帽(字符字符串[]){
INT I;
INT X = strlen的(字符串); //你要得到整个字符串的长度。
对于(i = 1; I< X,我++){
如果(因而isalpha(串[I])及&放大器;串[I-1] ==''){
//单词的只有第一个字母。
字符串[我] = TOUPPER(字符串[我]);
}
}
}主要(){
字符字符串[] =TEXT小写的话。
帽(字符串);
的printf(%S,字符串);
};不过文本的第一个字是小写。这是给你一个任务。
I'm pretty new to C and am hitting a wall when creating the below function. I want to use this function to make the first letter of a word upper case for a static character array (char string[]. It looks ok to my eye, but I'm getting some syntax errors which are probably pretty basic. compiler errors:
error: invalid conversion from
const char' to
const char*' initializing argument 1 of `size_t strlen(const char*)' assignment of read-only location
void Cap(char string[]){ int i; int x = strlen(string); for (i=1;i<x;i++){ if (isalpha(string[i]) && string[i-1] == ' '){ // only first letters of a word. string[i]= toupper(string[i]); }if (isalpha(string[0])) { string[0]=toupper(string[0]); } } }
解决方案I took your code and tried to compile it. Well, it would be nice to see compilable code the next time. Here is one with comments.
#include <stdio.h> // Now I am able to use printf. #include <string.h> // I was not able to use strlen without this... void Cap(char string[]){ int i; int x = strlen(string); // You want to get the length of the whole string. for (i=1;i<x;i++){ if (isalpha(string[i]) && string[i-1] == ' '){ // only first letters of a word. string[i]= toupper(string[i]); } } } main(){ char string[] = "text with lowercase words."; Cap(string); printf("%s",string); };
Still the first word of the text is lowercase. This is a task for you.
这篇关于C函数大写单词的第一个字母在一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!