C语言 C函数将数组中单词的第一个字母大写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20036553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 10:19:34  来源:igfitidea点击:

C function to capitalize first letter of words in an array

carraysstringfunctiontoupper

提问by 4reel77

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:

我对 C 很陌生,并且在创建以下函数时碰壁了。我想使用此函数为静态字符数组 (char string[]) 制作大写单词的第一个字母。在我看来,它看起来不错,但我遇到了一些可能非常基本的语法错误。编译器错误:

error: invalid conversion from const char' toconst char*' initializing argument 1 of `size_t strlen(const char*)' assignment of read-only location

错误:从const char' toconst char*' 初始化参数 1 的'size_t strlen(const char*)' 分配的只读位置无效转换

  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]);
                        }
         }
}

采纳答案by Stefan Bollmann

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.

文本的第一个单词仍然是小写。这是给你的任务。

回答by ordahan

you might want to run strlen(string)- as strlen(string[i])is trying to get the length of a single char.

您可能想要运行strlen(string)- 就像strlen(string[i])尝试获取单个字符的长度一样。

回答by kjhf

I will also point out your braces don't match ...

我也会指出你的大括号不匹配......

if (isalpha(string[i])){
       string[i]= toupper(string[i]);

Remove brace on the if line or put a close brace after your assigning statement.

删除 if 行上的大括号或在赋值语句后放置一个右大括号。

回答by tychon

You're missing the closing curly brace for your if statement. This might just be a typo in the question, but mentioning it just in case.

您缺少 if 语句的右花括号。这可能只是问题中的一个错字,但提一下以防万一。

Your function is declared void. This means it returns nothing. Any return statement should have nothing after the word since the function returns nothing, and in many cases you won't have a return statement at all.

您的函数被声明为无效。这意味着它什么都不返回。任何 return 语句在单词后都不应有任何内容,因为该函数不返回任何内容,而且在许多情况下,您根本不会有 return 语句。

However, the biggest issue is that this isn't an array of strings. It's an array of chars, which is just one string. char* stringand char string[]both (potentially) refer to an array of characters, which makes up a single string. You would need to use another level of indirection to refer to an array of array of characters: char** strings, char* strings[], or char strings[][]. The last form would require you specify how long all the strings could be, so you'd usually only use the first two.

然而,最大的问题是这不是一个字符串数组。它是一个字符数组,它只是一个字符串。char* string并且char string[]两者(可能)都是指一个字符数组,它构成一个字符串。您可能需要使用的间接另一个层面是指字符数组的数组:char** stringschar* strings[]char strings[][]。最后一种形式需要您指定所有字符串的长度,因此您通常只使用前两个。

回答by wybourn

The problem here is that you are passing in a single string, not an array of strings.

这里的问题是您传入的是单个字符串,而不是字符串数组。

Basically in C, a string is an array of chars, hence an array of strings is a two dimensional array like so:

基本上在 C 中,字符串是一个字符数组,因此字符串数组是一个二维数组,如下所示:

const char* strings[];

There are a few other issues with the code. You haven't initialized i before using it.

代码还有一些其他问题。你在使用之前没有初始化 i 。

回答by ryyker

A alternateapproach: (write a function)

替代的方法:(写的函数)

1)(optional) Allocate memory for new buffer of same length for results in calling function.
2)In function - Set first char of new string to upper case version of original string
3)Walk through the string searching for spaces.
4)For each space, Set next char of new string to upper case of char in original string
5)Loop on 4) until NULL detected
6)Free any allocated memory in calling program.

1)(可选)为调用函数的结果分配相同长度的新缓冲区的内存。
2)在函数中 - 将新字符串的第一个字符设置为原始字符串的大写版本
3)遍历字符串搜索空格。
4)对于每个空格,将新字符串的下一个字符设置为原始字符串中字符的大写
5)循环 4) 直到检测到 NULL
6)在调用程序中释放任何已分配的内存。

Code example:

代码示例:

void capitalize(char *str, char *new)
{
    int i=0;

    new[i] = toupper(str[0]);//first char to upper case
    i++;//increment after every look
    while(str[i] != '
#include <stdio.h>
#include <string.h>

capital(char s[])
{
    int i;
    for(i=0; i<strlen(s); i++)
    {
        if (i==0||s[i-1]==' '&&s[i]>='a'&&s[i]<='z')
            s[i]=toupper(s[i]);
    }
    puts(s);
}

main()
{
    char s[100];
    printf("Enter a line: ");
    gets(s);
    capital(s);
}
') { if(isspace(str[i])) { new[i] = str[i]; new[i+1] = toupper(str[i+1]);//set char after space to upper case i+=2;//look twice, increment twice } else { new[i] = str[i];//for no-space-found, just copy char to new string i++;//increment after every look } } }

回答by A.K. Tarafder

This should work just fine.

这应该工作得很好。

#include <string.h>
#include <stdio.h>

char* uc_words(char string[])
{
    int i;
    int x = strlen(string);
    int counter = 0;

    for (i = 0; i < x; i++)
    {
        // If found a white-space reset counter
        if (isspace(string[i]))
            counter = 0;

        // Check if first character in word
        if (isalpha(string[i]) && !isspace(string[i]) && counter == 0)
        {
            string[i]= toupper(string[i]);
            counter = 1;
        }
    }

    return string;
}

int main()
{
    char string[] = "hello world";
    printf("%s\n", uc_words(string));

    return 0;
}

回答by Crazenezz

I made an update based on Stefan Bollmannanswer:

我根据Stefan Bollmann 的回答进行了更新:

##代码##