c語言之字符串數組


一、字符串與字符串數組

  1、字符數組的定義

    char array[100];

  2、字符數組初始化

    char array[100] = {'a','b','c'};  //array[0] = 'a'    array[10] = 0

    char aray[100] = "abcdef"; 

    char aray[100] = {0};

    char aray[] = "qwertyuiop"; //未指定長度時,根據字符串長度自動填寫。

  3、sizeof()方法 查看數組的字節長度 

    例如:

#include<stdio.h>
int main(void) { char a[] = "asdfg"; int len = sizeof(a); printf("數組a的長度為:%d",len); //數組a的長度為:6 --> "asdfg\0"(實際上字符串以數字0結尾) return 0; }

  4、字符數組的使用

    例一:排序  

#include<stdio.h> 

int main(void) { char a[] = "befacd"; char i,j,temp; for(i=0;i<sizeof(a)-1;i++) { for(j=1;j<sizeof(a)-1-i;j++) { if(a[j-1]>a[j]) { temp = a[j-1]; a[j-1] = a[j]; a[j] = temp; } } } printf("%s\n",a); // 輸出: abcdef 

    return 0; }
View Code

     例二:字符串倒置(首尾倒置)

#include<stdio.h> 
int main(void) { char str[] = "hello world"; int i = 0; while(str[i++]) ; int len = i-1;  //字符串有效長度 
    int min = 0; int max = len-1; // 下標最大值 
    while(min<max) { char temp = str[min]; str[min] = str[max]; str[max] = temp; min++; max--; } printf("%s\n",str); // 輸出: dlrow olleh 
    return 0; }
View Code

    例三:漢字首尾逆置

#include<stdio.h> 
int main(void) { char b[] = "你好!明天"; //每個中文字符在gbk編碼中占兩個字節 int i = 0; while(b[i++]) ; //不斷遍歷字符串,直至遇到末尾的0,退出 i--; // 字符串的有效長度 int min = 0; int max = i-1; while(min<max) { char tmp; tmp = b[min]; //調換第一個字節和倒數第二個字符 b[min] = b[max-1]; b[max-1] = tmp; tmp = b[min+1]; //調換第二個字節和最后一個字符 b[min+1] = b[max]; b[max] = tmp; min += 2; max -= 2; } printf("倒置后的字符串:%s\n",b);   // 倒置后的字符串:天明!好你
     
    return 0; }

    例四:混合統計漢字和ASCII字符串字符  

#include<stdio.h>
int main(void) { char str[] = "厲害了,MyCountry!"; int len_e = 0; int len_c = 0; int sum = 0; int i,j; while(str[i]) { if(str[i]<0) { len_c += 1; i += 2; } else{ len_e += 1; i += 1; } } sum = len_c+len_e; printf("中文字符:%d,英文字符:%d,所有字符總數:%d",len_c,len_e,sum); //中文字符:4,英文字符:10,所有字符總數:14 
    return 0; }

    例五:去除字符串右邊的空格

#include<stdio.h> 
int main(void) { char c[100] = "hello "; int i = 0; int len,j; while(c[i++]) ; len = i--; for(j=len;j>0;j--) { if(c[j]!=' ') { c[j++]=0; break; } } printf("取掉末尾的空格后的字符串:%s\n",c); //取掉末尾的空格后的字符串:hello
    return 0; }

    例六:去除字符串前面的空格

#include<stdio.h>
int main(void) { char s[100] = " hello,boy"; int count = 0;  //統計空格長度 
    int i; while(s[count++]==' ') //遍歷空格 
    count--; //取得空格數量 
    i = count; //字符開始位置 
    while(s[i]) { s[i-count] = s[i]; //第一個字符賦給第一個位置
        i++; } s[i-count] = 0; //字符串最后賦0
    printf("去除空格后的字符串:%s\n",s); return 0; }
View Code

   4、數組總結

    1、數組的本質就是一次定義多個類型相同的變量,同時一個數組中所有的元素在內存中都是順序存放的。
    2、char s[100] ;s[0]-->s[99],切記沒有s[100]這個元素。並且c語言編譯器不會幫你檢查下標是否有效。
    3、字符串一定是在內存中以0結尾的一個char數組。

 

 

 

    

    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM