首页 > 解决方案 > 如何在C程序中将字符串中的第一个单词和最后一个单词大写?

问题描述

我正在编写关于字符串的 ac 程序。当我想利用字符串中的第一个单词和最后一个单词时,我遇到了麻烦。任何人都可以帮助我,请。非常感谢。这是我的代码:

#include <stdio.h> 
void fun(int tc, char []);
int main() {
        int tc;
        char string[100];
        printf("Enter tc: ");
        scanf("%d", &tc);
        fflush(stdin);
        printf("Enter a string:\n");
        gets(string);
        printf("\nThe original string: \n%s", string);
        fun(tc, string);
        printf("\n\nThe string after processing: \n%s", string);
        printf("\n\nOutput: \n%s", string);
        return 0;
} 
void fun(int tc ,char s[]) {
        int c = 0;
        int spaceCounter = 0; //First word not to be capitalized
        while (s[c] != '\0')
        {
                if(tc == 1){
                        if ((spaceCounter  == 0) && s[c] >= 'a' && s[c] <= 'z')
                        {
                                s[c] = s[c] - 32; // You can use toupper function for the same.
                        }
                        else if(s[c] == ' ')
                        {
                                spaceCounter++; //Reached the next word
                        }
                        c++;
                }
        }
}

标签: cstring

解决方案


假设您的字符串是s. 您可以从头开始大写,直到到达一个空格,这意味着第一个单词已经结束。然后你可以找到字符串的结尾并开始向后处理,直到找到一个空格,这意味着最后一个单词结束了。

void capitalize(char *s) 
{
    // capitalize first word
    while (!isspace(*s))
    {
        *s = toupper(*s);
        s++;
    }

    // reach end of s
    while(*s++);

    // capitalize last word
    s--;
    while (!isspace(*s))
    {
        *s = toupper(*s);
        s--;
    }
}

编辑:如果字符串至少有两个单词,则代码将起作用。在每个循环中添加对空终止符的检查以使其安全。


推荐阅读