练习1-19 编写函数 reverse(s),将字符串s 中的字符顺序颠倒过来。使用该函数编写一个程序,每次颠倒一个输入行中的字符顺序。

自己的:

思路

最开始的思路是在函数里新建一个字符数组,将输入的数组反过来存进这个新的数组里,再将新数组里的值赋到原数组中。

源代码

#include

#define MAXLINE 1000

int getline(char s[],int lim);
void reverse(char s[],int l);

/*
    Write a function reverse(s) that reverses the character string s.
    Use it to write a program that reverses its input a line at a time. 
*/
main()
{
    char line[MAXLINE];   //当前行
    int len;            //当前行长度

    while((len = getline(line,MAXLINE)) > 0)
    {
        reverse(line,len);
        printf("%s\n",line);
    }
    return 0;
}

//翻转字符串
void reverse(char s[],int l)
{
    char t[MAXLINE];
    int i = l;
    for(int j = 0; j < l;j++)
    {
        t[j] = s[i-2];
        i--;
    }
    for(int k = 0;k//获取输入行(此段为标准答案中的函数)
int getline(char s[],int lim)
{
    int c,i,j;

    j = 0;
    for(i = 0;(c = getchar()) != EOF && c != '\n';++i)
        if(i < lim - 2)
        {
            s[i] = c;
            ++j;            
        }
    if(c == '\n')
    {
        s[j] = c;
        ++i;
        ++j;
    }
    s[j] = '\0';
    return i;
}

遇到的错误:

将主函数中的while((len = getline(line,MAXLINE)) > 0)写成while(len = getline(line,MAXLINE) > 0)

少写了括号,先执行了大于号才执行了赋值号。

将reverse()函数中t[j] = s [i-2]写成t[j] = s[i-1].

执行时多输出了一个空行,因为s[i-1]存储的是换行符。

笔记

当我在调试时,在reverse函数中printf了s[i],发现它并不是s[i]的值,或许是地址?

接上,其实是因为我使用printf时使用了%d而不是%c。

标准答案:

思路

直接在同一字符串中翻转,使用一个中间变量,将字符串头尾对换。

源代码

/* reverse: reverse string s   */
void reverse(char s[])
{
    int i,j;
    char temp;

    i = 0;
    while(s[i] != '\0')  /* find the end of string s */
        ++i;
    --i;                /* back off from '\0'  */
    if(s[i] == '\n')
        --i;            /* leave newline in place  */
    j = 0;
    while(j < i)
    {
        temp = s[j];
        s[j] = s[i];    //swap the characters
        s[i] = temp;
        --i;
        ++j;
    } 
}

你可能感兴趣的:(the,c,programming,language)