[英]I need help understanding the code for reversing a string
我需要帮助理解一个用于反转字符串数组的函数。
我一直在查看一些代码,只是试图理解它。 它是一个使用指针的函数。
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;
}
}
我期待它反转一个字符串; 我有一个使用它的main
功能。
C 中的字符串是以零字符'\\0'
结尾的字符序列。
所以这个循环
while(pStr[i]!='\0')
{
length++;
i++;
}
计算字符串的长度,即字符串中零字符之前的字符数。 您可以使用标头<string.h>
声明的标准 C 函数strlen
代替循环。
这个循环
for (int i = 0; i < length / 2; i++) {
char temp = pStr[length - i - 1] ;
pStr[length - i - 1] = pStr[i];
pStr[i] = temp;
}
将字符串前半部分的字符与字符串后半部分的字符交换。 即第一个字符与最后一个字符交换,第二个字符与最后一个字符交换,依此类推,直到字符串的中间。
该函数有几个缺点。 可以按以下方式编写(不使用标准 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 ) );
}
程序输出是
Prachi Rajesh Jansari
irasnaJ hsejaR ihcarP
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.