用指针的方法,将字符串“ABCD1234efgh”前后对调显示

用指针的方法,将字符串“ABCD1234efgh”前后对调显示

加上注释谢谢

#include <stdio.h>
#include <string.h>

int main()
{
char TestString[] = "ABCD1234efgh";
char *pString = TestString;
int length = 0;

//计算字符串长度
for (int i = 0; TestString[i]; i++)
{
length++;
}

//字符串前后对调
for (int i = 0; i < length / 2; i++) //因为是对调,所以调换长度的一半,就完成了
{
char temp;
temp = *(pString + i); //头部的字符保存到temp中
*(pString + i) = *(pString + length - 1 - i); //使用尾部字符覆盖头部字符
*(pString + length - 1 - i) = temp; //使用temp(保存的头部字符)覆盖尾部字符
}

//显示输出
puts(TestString);

return 0;
}

//测试输出:
//hgfe4321DCBA

温馨提示:答案为网友推荐,仅供参考