1. 程式人生 > >如何進行字串的倒序排列

如何進行字串的倒序排列

如何進行字串的倒序排列

 

本次實驗是字串的倒序排列,在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:%s\n", 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 = '\0'; /*尾部要加'\0'*/
21     printf("after:%s\n", std);
22 
23     free(std); /*使用完,應該釋放空間,以免造成記憶體洩漏*/
24     std = NULL; /*防止產生野指標*/
25 }
26 
27 /*方法二:*/
28 static int string_t2(void)
29 {
30     char t;
31     char str[] = "Are you ok!";
32 
33     printf("before:%s\n", str);
34 
35     //int len = sizeof(str)-1;
36     int len = strlen(str);
37 
38     for(int i = 0; i < len/2; i++)
39     {
40         t = str[i];
41         str[i] = str[len-i-1];
42         str[len-i-1] = t;
43     }
44     printf("after:%s\n", str);
45 }
46 
47 int main(int argc, char const *argv[])
48 {
49     string_t1();
50     string_t2();
51 
52     return 0;
53 }

 

二、實驗結果

說明:實驗編譯環境Ubuntu,如果沒有安裝Ubuntu或者CentOS, 在網上自行下載VC++6.0中文版或者Visual Studio(VS2013)進行安裝後編譯。

&n