简体   繁体   English

我需要帮助理解反转字符串的代码

[英]I need help understanding the code for reversing a string

I need help understanding a function for reversing the array of string.我需要帮助理解一个用于反转字符串数组的函数。

I have been looking through a few codes, and just trying to understand it.我一直在查看一些代码,只是试图理解它。 It is a function using a pointer.它是一个使用指针的函数。

void ReverseString(char *pStr){
    int length = 0;
    int i = 0;

    while(pStr[i]!='\0')
    {
        length++;
        i++;
    }

    for (int i = 0; i < length / 2; i++) {
        char temp = pStr[length - i - 1] ;
        pStr[length - i - 1] = pStr[i];
        pStr[i] = temp;
    }
}

I am expecting it to reverse a string;我期待它反转一个字符串; I have a main function that uses it.我有一个使用它的main功能。

Strings in C are sequences of characters terminated with a zero character '\\0' . C 中的字符串是以零字符'\\0'结尾的字符序列。

So this loop所以这个循环

while(pStr[i]!='\0')
{
    length++;
    i++;
}

calculates the length of the string that is how many characters there are in the string before the zero character.计算字符串的长度,即字符串中零字符之前的字符数。 Instead of the loop you could use standard C function strlen declared in header <string.h> .您可以使用标头<string.h>声明的标准 C 函数strlen代替循环。

This loop这个循环

for (int i = 0; i < length / 2; i++) {
    char temp = pStr[length - i - 1] ;
    pStr[length - i - 1] = pStr[i];
    pStr[i] = temp;
}

swaps character from the first half of the string with characters of the second half of the string.将字符串前半部分的字符与字符串后半部分的字符交换。 That is the first character is swapped with the last character, the second character is swapped with the before last character and so on until the middle of the string.即第一个字符与最后一个字符交换,第二个字符与最后一个字符交换,依此类推,直到字符串的中间。

The function has several drawbacks.该函数有几个缺点。 It could be written (without using standard C functions) the following way可以按以下方式编写(不使用标准 C 函数)

#include <stdio.h>

char * ReverseString( char *pStr )
{
    size_t n = 0;

    // Calculates the number of characters in the string 
    // excluding the zero character.
    // SO the variable n will contain the number of characters in the string. 
    while ( pStr[n] != '\0' ) ++n;

    // Swaps characters from the first half of the string with 
    // the characters of the second half of the string.
    // So the loop has only n / 2 iterations. 
    for ( size_t i = 0; i < n / 2; i++ ) 
    {
        char c = pStr[n - i - 1] ;
        pStr[n - i - 1] = pStr[i];
        pStr[i] = c;
    }

    return pStr;
}

int main( void ) 
{
    char s[] = "Prachi Rajesh Jansari";

    puts( s );
    puts( ReverseString( s ) );
}

The program output is程序输出是

Prachi Rajesh Jansari
irasnaJ hsejaR ihcarP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM