Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the methods of obtaining string length in C language

Shulou Source: shulou.com Published: 2022-06-01 01:49:05 10月01日 Update

This article mainly introduces the relevant knowledge of the method of obtaining string length in C language, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this article on the method of obtaining string length in C language. Let's take a look.

First, use the sizeof () operator

In C language, sizeof () is the operator of length, and you can put data types or expressions in parentheses, which we usually use to calculate the length of a string.

Basic usage:

Int iTunes 10 str sizeof (I); / / expression char str [] = "hello world"; sizeof (str); sizeof (double); / / data type

When using sizeof () to calculate the length of a string,'"is also calculated into the length of the string. For example," abcd "calculates the length with sizeof () to get 5.

Note: char str [100] = ""; the value of sizeof (str) is 100.

Second, use strlen function

Functions for calculating the length of strings are provided in string.h.

Syntax:

Size_t strlen (const char * str)

When using the strlen function, you need to add a string.h header file, which calculates the length of the string and does not include'".

Third, write functions

If you don't want to use sizeof () and strlen (), you can use a loop to determine the length of the string.

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

This function returns a length numeric value by passing in a string.

Test the code:

# include # include int get_length (char str []) {char * p = str; int count = 0; while (* paired +! = ") {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", count1); printf ("use strlen the length is d", count2); printf ("use get_length the length is d", count3); return 0;}

Results:

This is the end of the article on "what are the methods of obtaining string length in C language?" Thank you for reading! I believe you all have a certain understanding of the knowledge of "what are the methods of obtaining string length in C language". If you want to learn more, you are welcome to follow the industry information channel.

Tags: Length character string function language method knowledge content data article type expression operator operation code value accounting parenthesis simple operation numerical value Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn MariaDB Xiaomi Linux Huawei