How to determine string length (without using strlen ())

size_t stringlength(const char *s)

Using this function, how can I find the length of a string? I do not mean use strlen(), but create it. Any help is appreciated.

+2
source share
4 answers

Loop / iterate over the line, account management. When you click \0, you have reached the end of your line.

Key concepts include a loop, a conditional (to check the end of a line), a counter, and access to items in a sequence of characters.

: / . OP C ( , ), , , , , / , OP :) downvote (, " ", . - , ).

. , .

+10
size_t stringlength(const char *s) {
   size_t count = 0;
   while (*(s++) != '\0') count++;
   return count;
}

*(s++), , ++, *, . :

size_t stringlength(const char *s) {
   size_t count = 0;
   while (s[count] != '\0') count++;
   return count;
}

( ):

size_t stringlength(const char *s) {
   size_t count = 0;
   while (*s++) count++;
   return count;
}


size_t stringlength(const char *s) {
   const char* c = s;
   for (; *c; c++);
   return c - s;
}

, , , , ( glibc-, , 4 )

+2

, , . ...

int a[] = {1,2,3,4,5,6};

unsigned int i,j;

i = &a; //returns first address of the array say 100

j = &a+1; //returns last address of the array say 124

int size = (j-i)/sizeof(int); // (j-i) would be 24 and (24/4) would be 6

//assuming integer is of 4 bytes

printf("Size of int array a is :%d\n",size);

:

char a[] = "Hello";

unsigned int i,j;

j = &a+1; //returns last address of the array say 106

i = &a; //returns first address of the array say 100


printf("size of string a is : %d\n",(j-i)-1); // (j-i) would be 6

If you are confused, then how come a + 1 returns the last address of the array, check this link.


0
source

Assuming s is a non-bubble pointer, the following function traverses s from the beginning until a null zero is found. For each character that has passed s++;, the score increases count++;.

size_t stringlength(const char *s) {
   size_t count = 0;
   while (*s) {
     s++;
    count++;
   }
   return count;
}
-1
source

Source: https://habr.com/ru/post/1669507/


All Articles