C implementation - store string data and output in reverse order (specifically)

Code

        Idea: statically initialize the character array to store the string data, and then use the pointer to exchange the corresponding front and rear position elements, and then output. (The program has been annotated in detail and will not be repeated here)

//导入头文件
#include <stdio.h> 

//字符交换函数
void reverse(char* s){  
    int len = 0;//记录长度 
    char* p = s;//指针标记当前数据 
    while (*p != 0){ len++; p++; } //统计长度 
    for(int i=0;i<=len/2 -1;i++){ // 交换字符
    	char c;//中间变量
        c = *(s + i);
        *(s + i) = *(s + len - 1 - i);
        *(s + len - 1 - i) = c;
	}
}

//主函数
int main(){
    char s[] = "have a good time";//定义并初始化字符数组 
    printf("初始字符串为:%s\n", s);//输出结果
    reverse(s);//字符串逆序 
    printf("逆序后为:%s\n", s);//输出结果
    return 0;
}

operation result

Guess you like

Origin blog.csdn.net/m0_54158068/article/details/124392973