21xrx.com
2024-04-16 20:02:27 Tuesday
登录
文章检索 我的文章 写文章
C中的字符串长度
2021-07-07 08:22:38 深夜i     --     --
C

C程序求一个字符串的长度,例如“C程序设计”字符串的长度是13(空格字符也算)。 计算时不计算空字符。 要找到它,我们可以使用“string.h”的 strlen 函数。 C 程序不使用 strlen 函数,递归查找字符串的长度。

 

C语言中字符串的长度

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


int main()
{
  char a[100];
  int length;

  printf("Enter a string to calculate its length\n");
  gets(a);

  length = strlen(a);

  printf("Length of the string = %d\n", length);

  return 0;
}


下载字符串长度程序。

程序输出:

没有strlen的C中的字符串长度

您还可以在没有 strlen 函数的情况下找到字符串长度。 我们创建我们的函数来找到它。 如果字符不是空字符,我们扫描字符串中的所有字符,然后将计数器加一。 一旦找到空字符,计数器就等于字符串的长度。

#include <stdio.h>


int main()
{
  char s[1000];
  int c = 0;

  printf("Input a string\n");
  gets(s);

  while (s[c] != '\0')
    c++;

  printf("Length of the string: %d\n", c);

  return 0;
}

查找字符串长度的函数:
 

int string_length(char s[]) {
   int c = 0;


   while (s[c] != '\0')
      c++;

   return c;
}

C程序使用递归查找字符串的长度

#include <stdio.h>


int string_length(char*);

int main()
{
  char s[100];

  gets(s);

  printf("Length = %d\n", string_length(s));

  return 0;
}

int string_length(char *s) {
  if (*s == '\0') // Base condition
    return 0;

  return (1 + string_length(++s));
}

Function to find string length using pointers

int string_length(char *s) {
   int c = 0;
   
   while(*s[c] != '\0')
      c++;
     
   return c;
}

 

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章