[英]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.