c-将一个单词变成***符号



因此,任务是将句子中以大写字母开头的每个单词转换为"***"。

`

for (i = 1; input[i] != ''; i++)
if(isupper(input[i]))   input[i] = '***';
printf("n Changed sentence is:     %s", input);

`

这是我迄今为止编写的代码。它只能改变一个字符,但我不知道如何用整个单词来改变。

我假设input是一个正确分配的、以null结尾的C字符串。


您一次扫描(循环内(一个字符;类似地,您可以一次更改一个字符。

因此,如果解析的单词应该转换为星号序列,那么您需要一个额外的变量来存储。

当您在单词开头遇到大写字母时,变量设置为true。

当您遇到当前单词的末尾(空白(时,您将变量重置为false。

最后,您相应地更改(或不更改(当前角色。

查看代码中的注释

// you need a variable to record if the current word
// should be converted to a sequence of '*'
bool toAsterisk = false;
// sentence scanning loop (one character at a time)
// note that index starts at 0 (not 1)
for (i = 0; input[i] != ''; i++)
{
// check if the current word should be converted to asterisks
if( isupper( input[i] ) && toAsterisk == false )
{
toAsterisk = true;
}
// check if you rwach the end of the current word
if( input[i] == ' ' )
{
toAsterisk = true;
}
// convert to asterisks?
if( toAsterisk )
{
input[ i ] = '*';
}
}

以下是一个潜在的解决方案:

#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
char input[] = "The Mississippi river is very Wide.";
printf("%sn", input);
for(int i = 0; i < strlen(input); i++)
{
if((i != 0) && isupper(input[i]))
{
printf("*** ");
while(input[i] != ' ')
i++;
}
else
{
printf("%c", input[i]);
}
}
if(ispunct(input[strlen(input) - 1]))
printf("b%cn", input[strlen(input) - 1]);
else
printf("n");
return 0;
}

输出

$gcc-main.c-o main.exe/main.exe密西西比河很宽。***河非常***

通读这一行。如果字符是大写的,请输入while循环,直到得到空格或行尾,并将字符替换为*。

打印行。

#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char line[1024] = "This should Replace capitalized Words!";
int i = 0;
printf("line: %sn", line);
for (i = 0; i < strlen(line); i++) {
if (isupper(line[i])) {
while (line[i] != ' ' && line[i] != '' && isalpha(line[i])) {
line[i] = '*';
i++;
}
}
}
printf("line: %sn", line);
return 0;
}

输出

$ gcc -Wall -Werror test.c -o t
line: This should Replace capitalized Words!
line: **** should ******* capitalized *****!

根据评论中的反馈,这是我的版本,它不依赖于输入行长度或程序可用的内存。它实现了一个有限状态自动机,三个状态,用于检测第一个字母、下一个字母和非单词字母。以下可能的实施方式:

#include <stdio.h>
#include <ctype.h>
#define IDLE    (0)
#define FIRST   (1)
#define NEXT    (2)
int main()
{
int status = IDLE;
int c;
while ((c = getchar()) != EOF) {
if (isupper(c)) {
switch (status) {
case IDLE:
status = FIRST;
printf("***");
break;
case FIRST: case NEXT:
status = NEXT;
break;
} /* switch */
} else if (islower(c)) {
switch (status) {
case IDLE:
putchar(c);
break;
case FIRST: case NEXT:
status = NEXT;
} /* switch */
} else {
switch (status) {
case IDLE:
putchar(c);
break;
case FIRST: case NEXT:
putchar(c);
status = IDLE;
break;
} /* switch */
} /* if */
} /* while */
} /* main */

通过将一个字符更改为三个字符(将它们更改为三星(,可以更改字符串的长度。试着从那里开始。[此问题可能会影响循环的工作方式]

相关内容

最新更新