字符串系列之strlen函數

常用字符串處理函數有以下幾種:strlen   strncpy   strcpy   strncat    strcat   strncmp   strcmp   strstr。

這裏首先介紹strlen函數。

1.strlen(const cr *s)返回的是字符串的長度。獲得的是有效字符的長度,不包括末尾的結束符'\0'。

strlen函數的原型是:

unsigned int strlen(const char *str)
{
	assert(str != Null);
	unsigned int len = 0;
	while (*str++)
	{
		len++;
	}
	return len;
}

2.與sizeof的區別

sizeof是一個運算符,表示求對象在內存中佔用的字節數。對於字符串求sizeof,則字符串末尾的‘\0'也要計算在內,佔一個字節。

sizeof運算符參數可以是任何對象。而strlen函數的參數必須是const char*類型。

3.例子分析,下面是用strlen和sizeof的代碼分析

#include <iostream>
using namespace std;

int main()
{
	char str[] = "hello,world";
	char name[20] = "Jenny";
	char *ch = "hello";
	int len1 = strlen(str);
	int len2 = strlen(name);
	int len3 = strlen(ch);
	cout << "strlen:字符串長度 " << endl;
	cout << "str: " << len1 << endl;
	cout << "name: " << len2 << endl;
	cout << "ch: " << len3 << endl;
	cout << "sizeof: 內存字節數" << endl;
	cout << "str: " << sizeof(str) << endl;//這裏對字符串末尾的\0是佔用內存字節的,所以用sizeof求字節數比字符串長度大1.
	cout << "name: " << sizeof(name) << endl;
	cout << "ch: " << sizeof(ch) << endl;//因爲ch是指針,指針是地址,是佔用32位,也就是4個字節。與指針是何類型無關

	return 0;
}
輸出結果爲:
strlen:字符串長度
str: 11
name: 5
ch: 5
sizeof: 內存字節數
str: 12
name: 20
ch: 4
請按任意鍵繼續. . .

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章