c - 如何在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++;
}
}
}
解决方案
假设您的字符串是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--;
}
}
编辑:如果字符串至少有两个单词,则代码将起作用。在每个循环中添加对空终止符的检查以使其安全。
推荐阅读
- django - Django Rest 框架应用程序中的关注点分离/DI
- python - 如何解决参数助手(WatsonServicesAssistant)的参数?
- unity3d - 与 sketchfab/unit3d/Iray 相比,低多边形模型 tris 的渲染在 three.js 中显示非常困难/标记
- php - 单击登录后网站崩溃--未捕获的错误:在 null 上调用成员函数 prepare()
- android - 如何在不使用 xml 的情况下在 Kotlin 中以编程方式使用 AndroidX 导航架构组件?
- c# - 限制文件操作
- python - 仅通过插入和删除查找编辑距离的变化?
- sql - 如何删除特定列中包含 2 个或更少字符的行?
- python - 同时在同一个 Python Socket 上发送和接收是否是线程安全的?
- node.js - 使用 node-sass 和 Node.js 将 scss 编译成 css