简体   繁体   中英

Find length of string in C (without using strlen)

The code below does not print anything -

int main() {

        char *input = "This is a string";
        find_length(input);
        return 0;

}
void find_length(char *input){

    printf("%s", input);
    int length = 0;
    while(input[length]!='\0');
    {
        length++;
        printf("%i", length);
    }

}

You have an extra semicolon behind your loop:

while(input[length]!='\0');
                          ^ does not belong here!!!

So it is stuck in an infinite loop. Get rid of it.


Furthermore, there could be stream buffering. Try adding some \\n . Or call fflush(stdout) to flush the output stream.

void find_length(char *input){

    printf("%s\n", input);
    int length = 0;
    while(input[length]!='\0')  //  remove ;
    {
        length++;
        printf("%i\n", length);
    }

}

Yes it does, but since it does not print a newline the buffer doesn't get flushed until the program exits, and you will end up with a shell prompt on the same line. Some people have shell prompts with carriage returns, which would overwrite the program output.

Change this:

printf("...", ...);

To this:

printf("...\n", ...);

The following is solution.

#include <stdio.h>

int main()
{
 char str[100];
 printf("Enter a string: ");
 printf( "\rLength is: %d", printf("Entered string is: %s\n", gets(str)) - 20);
 return 0;
}

In the above program, gets() returns the entered string. We print the length using the first printf. The second printf() calls gets() and prints the entered string using returned value of gets(), it also prints 20 extra characters for printing “Entered string is: ” and “\\n”. That is why we subtract 20 from the returned value of second printf and get the length.

If you use for(int i=0; str[i];i++) this loop also runs as long as the elements inside array of characters are true not '\\0' . Which you can count it until '\\0 . In the code below you can see the same thing with while loop but when you return you should do -1 as when loop encounters '\\0' it terminates but it also adds 1 . If this confuses you, you can use same logic with for(length=0; ch[length];length++); then you don't have to do -1 ;

                #include <stdio.h>

                int strlength(char ch[]){
                    int length =0;
                    while(ch[length++]);
                    return length-1;
                }


                int main(){

                    char ch[20];
                    scanf("%s", ch);
                    // printf("%s", ch);
                    printf("%i\n",strlength(ch));
                    return 0;
                }

Easy way to find Length of the given string

int strLength(const char *_array)
  {
     int str_len=0;
        while(*(_array++))  
          str_len++;

        return str_len;
   }

This is your answer: (len will be lenght of string, string is the string!)

int len;
for(len=0; string[len]!='\0'; len++);
printf("Length of string is %i", len);

The question is old but...why are you bothering on creating a loop to get the length of the string as already printf can do that via the specifier %n :

#include <stdio.h>

int main(int argc, char* argv[])
{
    char *input = "This is a string";
    int length=0;
    printf("%s%n",input,&length);
    printf("\nThe length of \"%s\" is %d",input, length);
    return 0;
}

Or you can even get the output of the printf function after printing the string like that:

length=printf("%s",input);
printf("\nThe length of \"%s\" is %d",input, length);
C++, Count string without functions

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string leng;
    cout << "Enter String for Count" << endl;
    cin >> leng;
    int a = 0;
    while (leng[a++]);
    {
    cout << a;
    }
}

you can use of strlen source instead strlen Gnu C Compiler - GLIBC

#include <string.h>

size_t strlen (const char *str)
{
  int cnt;

  asm("cld\n"           /* Search forward.  */
      /* Some old versions of gas need `repne' instead of `repnz'.  */
      "repnz\n"         /* Look for a zero byte.  */
      "scasb" /* %0, %1, %3 */ :
      "=c" (cnt) : "D" (str), "0" (-1), "a" (0));

  return -2 - cnt;
}

note asm used to insert assembly in C source (also it's may be __asm__ )

我认为这就足够了:

sizeof(my_string)/sizeof(char)

Increment the length variable or remove semi-colon to while loop.

Try,

void find_length(char *input){
    int length = 0; /* declaration */

    printf("%s", input);
    while(input[length++]!='\0');
    printf("%i", length);
 }
 /* OR */
 void find_length(char *input){
    int length = 0;
    while(input[length]!='\0') 
    {
     length++;
     }
    printf("%i", length);
 }

I guess the other posts will point you to the right answer.

But I just want to drop one note here. It would be good if find_length() return the length of the string ( size_t or it could also be int ) instead of void

OTOH, you can look at the various other implementation of strlen() . Hope it helps!

#include <stdio.h>

// array version
int strlen1(char a[])
{
        int len = 0;
        while (a[len])
                len++;
        return len;
}

// pointer version
// *p++ = dereference the pointer value and then
// increment the pointer to the next memory location
int strlen2(char *p)
{
        int len = 0;
        while (*p++)
                len++;
        return len;

        /*              
        int *q = p;
        while (*p);
                p++;
        return p-q;
        */
}

int main()
{
        char s[] = "test string";
        char *p = "another string";

        printf("strlen1(%s) = %d \n", s, strlen1(s));
        printf("strlen1(%s) = %d \n", p, strlen1(p));

        printf("strlen2(%s) = %d \n", s, strlen2(s));
        printf("strlen2(%s) = %d \n", p, strlen2(p));

        return 0;
}
main(int argc, char *argv[])
{
    char *input = "Enter Any string";
    printf("your Entered String is: %s\n", input);

    int length = 0;
    while (input[length] != '\0') {
          length++;
    }

    printf("length is : %i\n", length); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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