欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C語言多種獲取字符串長度的方法

 更新時間:2021年07月22日 10:03:07   作者:小果沐雨  
這篇文章主要介紹了C語言多種獲取字符串長度的方法,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下

在C語言中,想要獲取字符串長度可以有很多方法,下面分別介紹

一、使用sizeof()運算符

在C語言中,sizeof() 是長度的運算符,括號中可以放入數(shù)據(jù)類型或者表達式,一般我們用來計算字符串長度。

基本用法:

int i=10;
sizeof(i);//表達式

char str[]="hello world";
sizeof(str);

sizeof(double);//數(shù)據(jù)類型

在使用sizeof()求字符串長度時,會將 ‘\0' 也計算到字符串長度中。例如"abcd"用sizeof()求長度會計算得到5。
注意:char str[100]=""; sizeof(str)的值是100。

二、使用strlen函數(shù)

在string.h中提供了計算字符串長度的函數(shù)。

語法:

size_t strlen(const char *str);

在使用strlen函數(shù)時,需要添加string.h頭文件,該函數(shù)會將字符串長度計算出,不包含 ‘\0'。

三、編寫函數(shù)

如果不想使用sizeof()和strlen(),可以利用循環(huán)來判斷字符串的長度。

int get_length(char str[])
{
	char *p = str;
	int count = 0;
	while (*p++ != '\0')
	{
		count++;
	}
	return count;
}

該函數(shù)通過傳入一個字符串,返回一個長度數(shù)值。

測試代碼:

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

int get_length(char str[])
{
	char *p = str;
	int count = 0;
	while (*p++ != '\0')
	{
		count++;
	}
	return count;
}

int main()
{
	char str[] = "abcd";
	int count1 = sizeof(str);
	int count2 = strlen(str);
	int count3 = get_length(str);
	printf("use sizeof the length is %d\n", count1);
	printf("use strlen the length is %d\n", count2);
	printf("use get_length the length is %d\n", count3);
	return 0;
}

結果:

在這里插入圖片描述

到此這篇關于C語言多種獲取字符串長度的方法的文章就介紹到這了,更多相關C語言獲取字符串長度內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論