c - 如何在C程序中将字符串中的第一个单词和最后一个单词大写?

标签 c string

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

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

最佳答案

假设您的字符串是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--;
    }
}

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

关于c - 如何在C程序中将字符串中的第一个单词和最后一个单词大写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53032572/

相关文章:

c - 如何制作50000位变量

c - 如何在 C 中的 UDP 客户端/服务器中向 sendto 和 recvfrom 添加延迟

c - 网站安全

c# - 如何将 TextBlock 文本属性设置为字符串资源?

php - 具有相同参数的相同函数的不同输出

c - AIX 运行时错误 : Symbol __dbargs (number 191) is not exported from dependent

c - 这两种内存分配有什么区别?

c - 字符串赋值的指针。错误: expression is unassignable

string - Lua string.find 找不到一行中的最后一个单词

c# - 取字符串的最后n行c#