gpt4 book ai didi

c - 如何在c中用点分隔符反转字符串中的单词并保持输出中的点

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

我想反转 c 中中间有点的字符串单词。

我尝试在c中使用for循环。

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

int main()
{
char str[100];
scanf("%s",str);
printf("%s",str);
int length = strlen(str);

// Traverse string from end
int i;
for (i = length - 1; i >= 0; i--) {
if (str[i] == '.') {

// putting the NULL character at the
// position of space characters for
// next iteration.
str[i] = '.';

// Start from next charatcer
printf("%s ", &(str[i]) + 1);
}
}

// printing the last word
printf("%s", str);

return 0;
}

输入示例

i.love.you

输出示例

you.love.i

最佳答案

这就是我的做法(省略错误检查):

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

int main(int argc, char *argv[])
{
char str[100];
char *c;

scanf("%s", str);

while ((c = strrchr(str, '.'))) {
*c = 0;
printf("%s.", c + 1);
}
printf("%s\n", str);

return 0;
}

输出:

$ ./a.out
this.is.a.test.for.stackoverflow
stackoverflow.for.test.a.is.this

关于c - 如何在c中用点分隔符反转字符串中的单词并保持输出中的点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58309637/

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