繁体   English   中英

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

[英]Finding the length of a Character Array in C

在 C 中,有人可以找到字符数组的长度的方法是什么?

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

如果char数组为null终止,

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

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

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结尾的字符串做的:它们在字符串的末尾放置一个'\\0'字符,以便您知道字符串何时结束)。

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

//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]));

祝一切顺利

如果你想要字符数组的长度使用sizeof(array)/sizeof(array[0]) ,如果你想要字符串的长度使用strlen(array)

你可以使用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));

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

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

您可以使用此功能:

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

通过说“字符数组”你的意思是一个字符串? 像“你好”或“哈哈哈,这是一串人物”..

无论如何,使用strlen() 阅读一下它,有很多关于它的信息,就像这里一样。

使用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;
}

好吧,11 年后,我在大学作业中遇到了这个问题。 我找到的解决方案无需更改作业要求的函数签名即可工作。

在我的情况下,我必须创建一个函数,如果项目存在或取决于 itemPrefix (例如香蕉的“B”)是否已经存在于字符数组 itemPrefixes 中,则返回项目索引以避免传递重复的前缀。

所以,我不得不使用for循环(或while循环) 问题是分配给了我每个函数的特定签名,并且对于该特定函数,它不允许我将main()函数上的count变量作为参数传递。

我不得不即兴发挥。

上面提到的两种方法都不起作用。 strlen()没有按预期工作,因为字符串没有'\\0'结束字符。 sizeof()方法也不起作用,因为它返回作为参数传入的字符数组指针的大小,而不是元素的数量。

所以,这就是我想出的功能。 一个简单的 while 循环,用于检查当前字符是否为NULL (或0 )。

void charArrLength(char array[]) {
    int arrLength = 0;
    
    while (array[arrLength] != 0) {
        arrLength++; //increment by 1
    } 
    
    printf("Character array has %d elements", arrLength);
}

但是,要使其工作,在main()函数中,您需要将字符数组声明为字符指针,然后根据您最终希望在数组中拥有的项目数分配所需的内存。

void charArrLength(char array[]) {
    int arrLength = 0; 
    
    while (array[arrLength] != 0) {
        arrLength++; 
    } 
    
    printf("Character array has %d elements", arrLength); //should give 33
} 

int main() { 
    char *array; //declare array as a pointer
    int arraySize = 33; //can be anything 
    
    array = (char*) malloc(arraySize * sizeof(char)); 
    
    charArrLength(array);

    free(array); //free the previously allocated memory
}

下面你会看到我是如何在我的作业中使用这个功能的。

首先,这是根据我的需要量身定制的上述功能。

int isItemExists(char itemPrefixes[], char itemPrefix) {
    int count = 0; //declare count variable and set to 0
    int itemIndex = -1; //declare item index variable and set it to -1 as default

    while (itemPrefixes[count] != 0) {
        count++;
    }

    for (int i = 0; i < count; i++) {
        if (itemPrefix == itemPrefixes[i]) {
            itemIndex = i; //if item exists, set item index to i
        }
    }

    return itemIndex;
}

然后,我如何在main()函数中声明itemPrefixes数组,以及如何根据n (用户想要添加到itemPrefixes数组的项目数)分配所需的内存。

char *itemPrefixes;
    
int n = 0; //number of items to be added variable

printf("> Enter how many items to add: ");
scanf("%d", &n);

//allocate n * size of char data type bytes of memory
itemPrefixes = (char*) malloc(n * sizeof(char));

最后,这是该功能的使用方式。

do {
    printf("\n\n> Enter prefix for item %d: ", i + 1);
    scanf(" %c", &itemPrefix);
    
    //prompt the user if that itemPrefix already exists
    if (isItemExists(itemPrefixes, itemPrefix) != -1) {
        printf("\nItem prefix already exists! Try another one.\n");
    }
} while (isItemExists(itemPrefixes, itemPrefix) != -1);

此外,在代码的最后,我释放了之前分配的内存。

free(itemPrefixes);

再次清除这一点,如果条件不同,这可能会容易得多。 该作业严格要求不将n作为参数传递。 尽管如此,我希望我能帮助其他可能在未来寻找这个的人!

只是为了它,如果有人看到这个并且有更简单的建议,请随时告诉我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM