一字符串与字符串数组
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"; // 未指定长度时, 根据字符串长度自动填写
3sizeof() 方法 查看数组的字节长度
例如:
- #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 数组的本质就是一次定义多个类型相同的变量, 同时一个数组中所有的元素在内存中都是顺序存放的
2char s[100] ;s[0]-->s[99], 切记没有 s[100] 这个元素并且 c 语言编译器不会帮你检查下标是否有效
3 字符串一定是在内存中以 0 结尾的一个 char 数组
来源: http://www.bubuko.com/infodetail-2524317.html