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结尾) return0;
}
  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];
c 字符串转数组
a[j] = temp;
}
}
}
printf("%s\n",a); // 输出: abcdef
return0;
}
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
return0;
}
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);  // 倒置后的字符串:天明!好你
return0;
}
    例四:混合统计汉字和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 return0;
}
    例五:去除字符串右边的空格
#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
return0;
}
    例六:去除字符串前⾯的空格
#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);
return0;
}
View Code
   4、数组总结
    1、数组的本质就是⼀次定义多个类型相同的变量,同时⼀个数组中所有的元素在内存中都是顺序存放的。
    2、char s[100] ;s[0]-->s[99],切记没有s[100]这个元素。并且c语⾔编译器不会帮你检查下标是否有效。
    3、字符串⼀定是在内存中以0结尾的⼀个char数组。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。