一、C风格字符串(C-Style String)
在内存中紧密排列的一串字符,以0结尾。以内存的首地址来代表该字符串,char*.C风格字符串不需要另外指定长度,规定以0作为结束。
二、字符串的几种存在方式:
1、字符数组
2、char*型指针
3、字符串常量 const char* str="hello";
三、字符串操作
1.遍历
#include<stdio.h>
int show_string(const char* str) {
for(int i=0;; i++) {
char ch=str[i];
if(ch==0) {
break;//发现结束符
}
printf("%c",ch);
}
return 0;
}
int main() {
const char* str="hello world";
show_string(str);
return 0;
}
2.字符串长度问题
字符串的长度:是指从头开始,一直到结束符,中间字符的个数
char str[128]={'h','e',0,'n','i'};//字符串长度2
char str[128]={0,'h','e','n','i'};//字符串长度0
#include<stdio.h>
void get_length(const char* str){
int count=0;
while(str[count]){
count++;
}
printf("%d\n",count);
}
int main(){
char* str="hello world";
get_length(str);
return 0;
}
3.字符串的复制
复制字符串是将一个字符串的内容复制到目标字符串中,包括结束符。(注:结束符之后的无效数据不能复制,目标缓冲区要足够大)
#include<stdio.h>
int main(){
char src[]="hello world";//源
char dst[128];//目标
int i=0;
while(1){
dst[i]=src[i];
if(src[i]==0){
break;
}
i++;
}
printf("%s\n",dst);
return 0;
}
4.字符串的比较
相等为0,大于1,小于-1