C reverse characters in a string

1. Topic

Write a function reverse_string(char * string) (recursive implementation)
implementation: reverse the characters in the parameter string.
Requirement: String manipulation functions in the C library cannot be used.

2. Program code

#define _CRT_SECURE_NO_WARNINGS 1

#include <stdio.h>
#include <Windows.h>
#include <assert.h>//assert函数是用来判断括号内是否为真,若不为真,
                        //则后面的程序不执行

int my_strlen(const char *string)//计算字符串长度的函数
{
    assert(string);

    int count = 0;

    while(*(string++))
    {
        count++;
    }
    return count;
}

void reverse_string(char *string)
{
    assert(string);

    int len = my_strlen(string);//求出字符串长度
    char temp = 0;

    if (len > 0)
    {
        temp = *string;//把该字符串的第一个字符赋给temp
        *string = string[len - 1];//把该字符串的最后一个字符赋给第一个位置
        string[len - 1] = '\0';//删掉最后面的字符
        reverse_string(string + 1);
        string[len - 1] = temp;//把此时的第一个字符赋给此时的最后一个位置
    } 
}

int main()
{
    char arr[20] = "0";

    printf("please input a character string:");
    scanf("%s", &arr);
    //printf("%d\n", my_strlen(arr));//测试求字符串长度的函数是否正确
    reverse_string(arr);
    printf("%s\n", arr);

    system("pause");
    return 0;
}

3. Execution results

write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325851366&siteId=291194637