Home > Backend Development > C++ > body text

How to calculate the length of string in C language

下次还敢
Release: 2024-04-30 00:48:14
Original
1067 people have browsed it

计算 C 语言中字符串长度的方法是:使用 strlen() 函数手动计算,遍历字符串并计数字符数量

How to calculate the length of string in C language

C 语言中字符串长度的计算

在 C 语言中,字符串是一种数据类型,表示由字符组成的序列。字符串的长度是指其中包含的字符数,不包括终止字符'\0'。

计算字符串长度的方法:

可以通过以下两种方法之一计算字符串的长度:

  • strlen() 函数:

    • 调用 strlen(str) 函数,其中 str 是指向字符串的指针。
    • 该函数返回字符串的长度,即到终止字符'\0'为止的字符数。
  • 手动计算:

    • 遍历字符串,逐个字符进行计数。
    • 循环直到遇到终止字符'\0',并记下遇到的字符数。

示例:

<code class="c">#include <stdio.h>
#include <string.h>

int main() {
  char str[] = "Hello, world!";

  // 使用 strlen() 函数
  int len1 = strlen(str);

  // 手动计算
  int len2 = 0;
  while (str[len2] != '\0') {
    len2++;
  }

  printf("字符串长度 (strlen()): %d\n", len1);
  printf("字符串长度 (手动计算): %d\n", len2);

  return 0;
}</code>
Copy after login

The above is the detailed content of How to calculate the length of string in C language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!