1. 程式人生 > >C語言字串處理基礎函式(一)

C語言字串處理基礎函式(一)

1.strlen()函式

功能:函式返回字串str 的長度( 即空值結束符之前字元數目,不包括控制結束符)。

語法:

 #include <string.h>
 size_t strlen( char *str );

例子:

#include <stdio.h>
#include <string.h>

int main()
{
	char *str1 = "hello world\n";
	char *str2 = "你好 中國!\n";

	printf("str1 len=%u,str2 len=%u\n",strlen(str1),strlen(str2));
	
	return 0;
}

結果:

注意:

1.strlen返回是size_t型別,即unsigned int,在標頭檔案stddef.h中定義

2.中文字元長度為三個位元組

2.不受限的字串函式strcpy(),strcat(),strcmp();

2.1 strcpy()

功能:複製字串src 中的字元到字串dest,包括空值結束符。返回值為指標dest
語法:

#include <string.h>
char *strcpy( char *to, const char *from );

例子:

#include <stdio.h>
#include <string.h>

int main()
{
	char str1[40] = "hello world,hello china";
	char *str2 = "你好 中國!";

	strcpy(str1,str2);

	printf("str1=%s,str2=%s\n",str1,str2);
	
	return 0;
}

結果:

注意:

1.使用strcpy函式時因為沒有長度限制,一定要確保str1的記憶體長度大於或者等於str2

2.如果st1裡面有字元會被覆蓋str2內容的長度,包括字串結束符。

2.2strcat()

功能:函式將字串str2 連線到str1的末端,並返回指標str1

語法:

 #include <string.h>
  char *strcat( char *str1, const char *str2 );

例子:

#include <stdio.h>
#include <string.h>

int main()
{
	char str1[40] = "hello world,hello china";
	char *str2 = "你好 中國!";

	strcat(str1,str2);

	printf("str1=%s,str2=%s\n",str1,str2);
	
	return 0;
}

2.3 strcmp();

功能:比較字串str1 and str2, 返回值如下:

返回值

解釋

less than 0(小於0)

str1 is less than str2

equal to 0(等於0)

str1 is equal to str2

greater than 0(大於0)

str1 is greater than str2

 

語法:

 #include <string.h>
  int strcmp( const char *str1, const char *str2 );

例子:

#include <stdio.h>
#include <string.h>

int main()
{
	char str1[40] = "hello world,hello china";
	char *str2 = "你好 中國!";

	printf("strcmp result=%d\n",strcmp(str1,str2));
	
	return 0;
}

3.長度受限的字串函式 strncpy(),strncat(),strncmp();

因為這三個函式與上面的函式功能一樣,只是多了一個長度的控制,其他的都是一樣的,所以這裡不在分開說明:

語法:

char *strncpy( char *to, const char *from, size_t count );
char *strncat( char *str1, const char *str2, size_t count );
int strncmp( const char *str1, const char *str2, size_t count );

例子:

#include <stdio.h>
#include <string.h>

int main()
{
	char str1[40] = "hello world";
	char *str2 = "你好 中國!";

	strncpy(str1,str2,6);
	printf("strncpy str1=%s\n",str1);

	strncat(str1,str2,6);
	printf("strncpy str1=%s\n",str1);

	printf("strncmp result=%d\n",strncmp(str1,str2,6));
	
	return 0;
}