gpt4 book ai didi

c - 在c中操作字符串

转载 作者:行者123 更新时间:2023-11-30 18:41:11 25 4
gpt4 key购买 nike

我试图从用户那里获取字符串输入,然后仅反转以元音开头的单词。然后重新打印更改后的字符串。我使用了 strtok() 函数将单词与字符串分开。但是反转单词,似乎是一个问题......我已经为这个程序编写了代码,但它有运行时错误。所以,如果有人可以帮助我纠正我的代码或为我提供解决方案,它将非常有用。

这是我的代码:

#include <stdio.h>
#include <string.h>

void reverse(char *tok);
int length(char *t);
int main()
{
char sen[50];
const char s[2] = " ";
int i;
printf("Enter a Sentence: ");
gets(sen);

char *token;
token = strtok(sen, s);
printf("Output: ");

while (token != 0)
{
char z[20] =
{ *token };
for (i = 0;; i++)
{
if (z[i] == ' ')
{
z[i] = '\0';
break;
}
}
if (z[0] == 'a' || z[0] == 'A' || z[0] == 'e' || z[0] == 'E' || z[0] == 'i'
|| z[0] == 'I' || z[0] == 'o' || z[0] == 'O' || z[0] == 'u'
|| z[0] == 'U')
{
reverse(token);
}
else
printf("%s ", *token);

token = strtok(NULL, s);
}
printf("\n");
return 0;
}

//function for reversing the particular parts of string
void reverse(char *tok)
{
char x[20] =
{ *tok };
int i, j, len;
char temp;

for (i = 0;; i++)
{
if (x[i] == ' ')
{
x[i] = '\0';
break;
}
}
len = length(tok);

j = len - 1;
for (i = 0; x[i] != len / 2; i++)
{
temp = x[i];
x[i] = x[j];
x[j] = temp;
j--;
}
printf("%s", x);
printf(" ");
}

//function for determining the length of the token string
int length(char *t)
{
int i = 0;
char y[20] =
{ *t };
for (;; i++)
{
if (y[i] == ' ')
{
y[i] = '\0';
break;
}
}

while (y[i] == '\0')
{
i++;
}
return i;
}

最佳答案

这一行

printf("%s ", *token);

传递一个char,其中需要以0结尾的char[]

吸取的教训是:始终在打开所有警告的情况下进行编译!(对于 gcc,-Wall -Wextra -pedantic)

关于c - 在c中操作字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22793371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com