C function to capitalize first letter of words in an array

℡╲_俬逩灬. 提交于 2019-11-28 10:03:55

问题


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

回答1:


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.




回答2:


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




回答3:


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.




回答4:


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.

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.

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* string and 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.




回答5:


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:

const char* strings[];

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




回答6:


A alternate approach: (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.

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] != '\0')
    {
        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
        }
    }
}



回答7:


This should work just fine.

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



回答8:


I made an update based on Stefan Bollmann answer:

#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;
}


来源:https://stackoverflow.com/questions/20036553/c-function-to-capitalize-first-letter-of-words-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!