简体   繁体   English

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

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

What is a way in C that someone could find the length of a character array?在 C 中,有人可以找到字符数组的长度的方法是什么?

I will happily accept pseudo-code, but am not averse to someone writing it out if they'd like to :)我很乐意接受伪代码,但我不反对有人写出来,如果他们愿意:)

Provided the char array is null terminated, 如果char数组为null终止,

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

If you have an array , then you can find the number of elements in the array by dividing the size of the array in bytes by the size of each element in bytes: 如果你有一个数组 ,那么你可以通过将数组的大小除以每个元素的大小(以字节为单位)来找到数组中元素的数量:

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

For the specific case of char , since sizeof(char) == 1 , sizeof(x) will yield the same result. 对于char的特定情况,由于sizeof(char) == 1sizeof(x)将产生相同的结果。

If you only have a pointer to an array , then there's no way to find the number of elements in the pointed-to array. 如果只有一个指向数组的指针 ,那么就无法找到指向数组中的元素数。 You have to keep track of that yourself. 你必须自己跟踪。 For example, given: 例如,给定:

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

there is no way to tell from just pointer_to_x that it points to an array of 10 elements. 没有办法告诉pointer_to_x它指向一个包含10个元素的数组。 You have to keep track of that information yourself. 您必须自己跟踪这些信息。

There are numerous ways to do that: you can either store the number of elements in a variable or you can encode the contents of the array such that you can get its size somehow by analyzing its contents (this is effectively what null-terminated strings do: they place a '\\0' character at the end of the string so that you know when the string ends). 有很多方法可以做到这一点:你可以在变量中存储元素的数量,或者你可以编码数组的内容,这样你就可以通过分析它的内容以某种方式得到它的大小(这实际上是以null结尾的字符串做的:它们在字符串的末尾放置一个'\\0'字符,以便您知道字符串何时结束)。

Hi although the above answers are OK, here's my contribution to your question. 嗨虽然上面的答案都没问题,但这是我对你的问题的贡献。

//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;
}

In function main you call function size by passing the address of the first element of your array. 在函数main中,通过传递数组的第一个元素的地址来调用函数大小。 For example: 例如:

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

All the best 祝一切顺利

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

You can use strlen 你可以使用strlen

strlen(urarray);

You can code it yourself so you understand how it works 您可以自己编写代码,以便了解它的工作原理

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

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

if you want the size of the array then you use sizeof 如果你想要数组的大小,那么你使用sizeof

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

There is also a compact form for that, if you do not want to rely on strlen. 如果你不想依赖strlen,还有一个紧凑的形式。 Assuming that the character array you are considering is "msg": 假设您正在考虑的字符数组是“msg”:

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

You can use this function:您可以使用此功能:

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

By saying "Character array" you mean a string? 通过说“字符数组”你的意思是一个字符串? Like "hello" or "hahaha this is a string of characters".. 像“你好”或“哈哈哈,这是一串人物”..

Anyway, use strlen() . 无论如何,使用strlen() Read a bit about it, there's plenty of info about it, like here . 阅读一下它,有很多关于它的信息,就像这里一样。

using sizeof() 使用sizeof()

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

using string.h 使用string.h

#include <string.h>

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

using function ( strlen implementation ) 使用函数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;
}

Well, 11 years later, I run into this issue with a college assignment.好吧,11 年后,我在大学作业中遇到了这个问题。 The solution I found, worked without having to alter the function signatures that the assignment was asking for.我找到的解决方案无需更改作业要求的函数签名即可工作。

In my case, I had to make a function that returns the item index if the item existed or depending on if the itemPrefix (eg 'B' for Banana) already exists or not in the character array itemPrefixes to avoid passing duplicate prefixes.在我的情况下,我必须创建一个函数,如果项目存在或取决于 itemPrefix (例如香蕉的“B”)是否已经存在于字符数组 itemPrefixes 中,则返回项目索引以避免传递重复的前缀。

So, I had to use a for loop (or while loop) .所以,我不得不使用for循环(或while循环) The problem was that the assignment had given me specific signatures for each function and for that specific function it didn't allow me to pass the count variable that was on the main() function as an argument.问题是分配给了我每个函数的特定签名,并且对于该特定函数,它不允许我将main()函数上的count变量作为参数传递。

I had to improvise.我不得不即兴发挥。

Both the ways mentioned above didn't work.上面提到的两种方法都不起作用。 strlen() didn't work as intended since there was not a '\\0' end character that strings have. strlen()没有按预期工作,因为字符串没有'\\0'结束字符。 The sizeof() method also didn't work, because it returned the size of the pointer of the character array that was passed in as an argument instead of the number of elements. sizeof()方法也不起作用,因为它返回作为参数传入的字符数组指针的大小,而不是元素的数量。

So, this is the function I came up with.所以,这就是我想出的功能。 A simple while loop that checks whether the current character is NULL (or 0 ).一个简单的 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);
}

For this to work though, in the main() function, you need to declare your character array as a character pointer and then allocate the memory that you need based on the number of items that you ultimately wish to have inside your array.但是,要使其工作,在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
}

Below you will see how I utilised this function in my assignment.下面你会看到我是如何在我的作业中使用这个功能的。

First, here is the above function tailored to my needs.首先,这是根据我的需要量身定制的上述功能。

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

Then, how I declared the itemPrefixes array in main() function and how I allocated the needed memory based on n (the number of items the user would like to add to itemPrefixes array).然后,我如何在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));

And finally, here is how that function was used after all.最后,这是该功能的使用方式。

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

Also, in the end of the code I free the previously allocated memory.此外,在代码的最后,我释放了之前分配的内存。

free(itemPrefixes);

To clear this out, again, this could be much easier if the conditions were different.再次清除这一点,如果条件不同,这可能会容易得多。 The assignment was strict about not passing n as an argument.该作业严格要求不将n作为参数传递。 Nevertheless, I hope I help someone else that might be looking for this in the future!尽管如此,我希望我能帮助其他可能在未来寻找这个的人!

Just for the sake of it, if anybody sees this and has something simpler to suggest, feel free to tell me.只是为了它,如果有人看到这个并且有更简单的建议,请随时告诉我。

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

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