0%

字符串反转

文章时效性提示

本文发布于 496 天前,部分信息可能已经改变,请注意甄别。

题目:字符串反转,如将字符串“Hello World”反转为”dlroW olleH”

代码一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <stdio.h>
void Char_Reverse(char* ch)
{
    int i = 0;
    while (ch[i] != '\0')
    {
        i++;
    }
    char temp[i];
    int j = 0;
    int x = i;
    for (j=0; j<i; j++)
    {
        temp[j] = ch[x-1];
        x--;
    }
    for (j=0; j<i; j++)
    {
        ch[j] = temp[j];
    }
}
int main()
{
    char ch[50];
    scanf("%s",ch);
    Char_Reverse(ch);
    printf("%s",ch);
    return 0;
}

但是这段代码无法反转带空格的字符串,原因是scanf遇到空格就停止读取了。
解决这个问题,使用%[^\n],表示读取除了换行符 \n 以外的所有字符,这样可以读取整行文本。


代码二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdio.h>
void Char_Reverse(char* ch)
{
    int i = 0;
    while (ch[i] != '\0') {
        i++;
    }
    char temp[i];
    int j = 0;
    int x = i;
    for (j=0; j<i; j++)
    {
        temp[j] = ch[x-1];
        x--;
    }
    for (j=0; j<i; j++) {
        ch[j] = temp[j];
    }
}
int main()
{
    char ch[50];
    scanf("%[^\n]",ch);
    Char_Reverse(ch);
    printf("%s",ch);
    return 0;
}

这里改进了scanf不能读取空格之后的问题。
输入Hello World
输出为dlroW olleH