在C语言中,如何编写反转行中字词的程序?创建一个源文件:program_to_reverse_words_in_line.c,参考以下实现代码 -
#include
#include
int string_length(char s[]) {
int i = 0;
while (s[i] != '\0')
i++;
return i;
}
void string_reverse(char st[]) {
int i, j, len;
char ch;
j = len = string_length(st) - 1;
i = 0;
while (i < j) {
ch = st[j];
st[j] = st[i];
st[i] = ch;
i++;
j--;
}
}
int main(void) {
char line[] = "Maxsu is one of the five wonders of the world";
char reverse[100] = "", temp[50];
int i, j, n;
n = string_length(line);
for (i = 0; i < n; i++) {
for (j = 0; i < n && line[i] != ' '; ++i, ++j) {
temp[j] = line[i];
}
temp[j] = '\0';
string_reverse(temp);
strcat(reverse, temp);
strcat(reverse, " ");
}
printf("Original - %s\n", line);
printf("Reversed - %s\n", reverse);
return 0;
}
执行上面示例代码,得到以下结果 -
Original - Maxsu is one of the five wonders of the world
Reversed - usxaM si eno fo eht evif srednow fo eht dlrow
¥ 我要打赏
纠错/补充
收藏
加QQ群啦,易百教程官方技术学习群
注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。