简体   繁体   English

在 C 中查找字符串的长度(不使用 strlen)

[英]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 .尝试添加一些\\n Or call fflush(stdout) to flush the output stream.或者调用fflush(stdout)来刷新输出流。

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.是的,它确实如此,但由于它不打印换行符,因此在程序退出之前缓冲区不会被刷新,并且您最终会在同一行上看到 shell 提示。 Some people have shell prompts with carriage returns, which would overwrite the program output.有些人有带回车的 shell 提示,这会覆盖程序输出。

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.在上面的程序中,gets() 返回输入的字符串。 We print the length using the first printf.我们使用第一个 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”.第二个 printf() 调用gets() 并使用gets() 的返回值打印输入的字符串,它还打印20 个额外的字符用于打印“输入的字符串是:”和“\\n”。 That is why we subtract 20 from the returned value of second printf and get the length.这就是为什么我们从第二个 printf 的返回值中减去 20 并得到长度的原因。

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' .如果您使用for(int i=0; str[i];i++) ,只要字符数组中的元素为 true 而不是'\\0'此循环也会运行。 Which you can count it until '\\0 .您可以将其计数到'\\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 .在下面的代码中,您可以看到与while循环相同的内容,但是当您返回时,您应该执行-1因为当循环遇到'\\0'它会终止,但它还会添加1 If this confuses you, you can use same logic with for(length=0; ch[length];length++);如果这让您感到困惑,您可以使用与for(length=0; ch[length];length++);相同的逻辑for(length=0; ch[length];length++); then you don't have to do -1 ;那么你不必做-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!)这是您的答案:(len 将是字符串的长度,字符串是字符串!)

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 :问题很老,但是......为什么你要费心创建一个循环来获取字符串的长度,因为printf已经可以通过说明符%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:或者您甚至可以在打印这样的字符串后获得printf函数的输出:

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您可以使用strlen源代码代替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__ )注意asm用于在 C 源代码中插入程序集(也可能是__asm__

我认为这就足够了:

sizeof(my_string)/sizeof(char)

Increment the length variable or remove semi-colon to while loop.增加length变量或删除分号到 while 循环。

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如果find_length()返回字符串的长度( size_t或者它也可以是int )而不是void会很好

OTOH, you can look at the various other implementation of strlen() . OTOH,您可以查看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); 
}

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

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