如何進行字元串的倒序排列

  • 2019 年 10 月 25 日
  • 筆記

如何進行字元串的序排列

 

本次實驗是字元串的倒序排列,在C語言中對字元串的操作可以說是無處不在,其作用不言而喻。下面就用2種不同的方法對字元串進行倒序排列。

 

一、實驗程式

 1 #include <stdio.h>   2 #include <string.h>   3 #include <stdlib.h>   4   5 /*方法一:*/   6 static int string_t1(void)   7 {   8     char *str = {"Hello, world!"};   9     printf("before:%sn", str);  10  11     int len = strlen(str);  12     char * std = (char *)malloc(len+1); /*要多分配一個空間*/  13     char *p = std;  14     char *s = &str[len-1];/*指向最後一個字元*/  15  16     while(len-- != 0)  17     {  18         *p++ = *s--;  19     }  20     *p = '