我想转换给定字符串中单词“welcome”的大小写。 所有发生的事情都应该被改变。 我尝试过的是下面的代码,
#include "stdio.h"
#include <string.h>
#include "ctype.h"
int main(int argc, char const *argv[]) {
printf("Enter the sentence you need to display via app:\n");
char sentence[100];
char word[10] = {"welcome"};
scanf("%[^\n]s", sentence);
getchar();
char * pch;
pch = strtok (sentence," ,.-");
while (pch != NULL)
{
if (strcmp(pch,word) == 0) {
while(*pch != '\0'){
*pch = toupper(*pch);
}
}
printf("%s\n", pch);
pch = strtok (NULL," ,.-");
}
printf("%s\n", sentence);
return 0;
}
/*
Output:
Enter the sentence you need to display via app:
welcome here welcome there
*/
该程序需要很长时间并且无法按预期工作。 提前致谢。
最佳答案
您的程序存在很多问题:
#include <stdio.h>
中标准包含文件的语法,使用<
和>
而不是"
.您应该定义
word
作为指针:const char *word = "welcome";
或一个没有长度的数组,让编译器为您计算:char word[] = "welcome";
.scanf
的语法字符范围是%[^\n]
,没有尾随s
。您应该将限制指定为%99[^\n]
.scanf()
如果输入空行将会失败。您应该测试返回值以避免读取失败时出现未定义的行为。使用
fgets()
会更安全读取一行输入。您不增加
pch
在循环中,因此无限循环需要永远执行。toupper
不得裸露char
,您必须转换char
至unsigned char
以避免产生未定义行为的潜在负值。strtok
已修改sentence
,您打印它只会打印第一个单词(以及任何前面的分隔符)。
这是更正后的版本:
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[]) {
char sentence[100];
char word[] = "welcome";
printf("Enter the sentence you need to display via app:\n");
if (fgets(sentence, sizeof sentence, stdin)) {
char *pch = strtok(sentence, " ,.-");
while (pch != NULL) {
if (strcmp(pch, word) == 0) {
char *p;
for (p = pch; *p != '\0'; p++) {
*p = toupper((unsigned char)*p);
}
}
printf("%s ", pch);
pch = strtok(NULL," ,.-");
}
printf("\n");
}
return 0;
}
关于将输入字符串中的单词 "welcome"更改为大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44759468/