在C中查找字符数组的长度

时间:2010-11-15 01:41:57

标签: c arrays

C中有什么方法可以找到Character数组的长度?

我很乐意接受伪代码,但如果他们愿意,我不反对写出来的人。)

9 个答案:

答案 0 :(得分:67)

如果char数组已null终止,

char chararray[10];
size_t len = strlen(chararray);

答案 1 :(得分:14)

如果您有数组,那么您可以通过将数组的大小除以每个元素的大小(以字节为单位)来找到数组中元素的数量:

char x[10];
int elements_in_x = sizeof(x) / sizeof(x[0]);

对于char的特定情况,由于sizeof(char) == 1sizeof(x)将产生相同的结果。

如果你只有一个指向数组的指针,那么就无法找到指向数组中的元素数量。你必须自己跟踪。例如,给定:

char x[10];
char* pointer_to_x = x;

没有办法告诉pointer_to_x它指向一个包含10个元素的数组。你必须自己跟踪这些信息。

有很多方法可以做到这一点:你可以在变量中存储元素的数量,或者你可以对数组的内容进行编码,这样你就可以通过分析它的内容来获得它的大小(这实际上是null-终止字符串do:它们在字符串的末尾放置一个'\0'字符,以便您知道字符串何时结束。)

答案 2 :(得分:8)

嗨虽然上面的答案都没问题,但这是我对你问题的贡献。

//returns the size of a character array using a pointer to the first element of the character array
int size(char *ptr)
{
    //variable used to access the subsequent array elements.
    int offset = 0;
    //variable that counts the number of elements in your array
    int count = 0;

    //While loop that tests whether the end of the array has been reached
    while (*(ptr + offset) != '\0')
    {
        //increment the count variable
        ++count;
        //advance to the next element of the array
        ++offset;
    }
    //return the size of the array
    return count;
}

在函数main中,通过传递数组第一个元素的地址来调用函数大小。 例如:

char myArray[] = {'h', 'e', 'l', 'l', 'o'};
printf("The size of my character array is: %d\n", size(&myArray[0]));

一切顺利

答案 3 :(得分:5)

如果您希望字符数组的长度使用sizeof(array)/sizeof(array[0]),如果您希望字符串的长度使用strlen(array)

答案 4 :(得分:4)

你可以使用strlen

strlen(urarray);

您可以自行编码,以便了解其工作原理

size_t my_strlen(const char *str)
{
  size_t i;

  for (i = 0; str[i]; i++);
  return i;
}

如果你想要数组的大小,那么你使用sizeof

char urarray[255];
printf("%zu", sizeof(urarray));

答案 5 :(得分:2)

如果您不想依赖strlen,还有一个紧凑的形式。假设您正在考虑的字符数组是" msg":

  unsigned int len=0;
  while(*(msg+len) ) len++;

答案 6 :(得分:0)

说“字符数组”是指字符串?像“你好”或“哈哈哈,这是一串人物”..

无论如何,请使用strlen()。阅读一下,有关它的大量信息,如here

答案 7 :(得分:0)

  

使用 sizeof()

char h[] = "hello";
printf("%d\n",sizeof(h)-1); //Output = 5
  

使用 string.h

#include <string.h>

char h[] = "hello";
printf("%d\n",strlen(h)); //Output = 5
  

使用功能strlen 实施

int strsize(const char* str);
int main(){
    char h[] = "hello";
    printf("%d\n",strsize(h)); //Output = 5
    return 0;
}
int strsize(const char* str){
    return (*str) ? strsize(++str) + 1 : 0;
}

答案 8 :(得分:0)

您可以使用此功能:

int arraySize(char array[])
{
    int cont = 0;
    for (int i = 0; array[i] != 0; i++)
            cont++;
    return cont;
}