1. 程式人生 > >C/C++----------深入瞭解字串

C/C++----------深入瞭解字串

一、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