Calculating string length not correct when not printing out the return value of a program

java string length limit
how to find length of string in java without using length() method
how to find length of string in java without using length() method
java substring
java string size in bytes
string length javascript
string length c++
charat (java)

Length is suppose to return how far along the counter went when going trough the string. However, it only returns the correct value when it is printed beforehand. If i comment out the printf it returns 0. Does anyone have an explanation for this?

#include<stdio.h>
#include<string.h>
#define MAX 100

int length(char *s) {
    int i;
    for (i = 0; s[i] != '\0'; ++i)
        printf("%d ", i);           //<-- here
    return i;
}

int main() 
{
    char s[MAX];
    fgets(s, (char)sizeof(s), stdin);
    s[strcspn(s, "\n")]='\0';
    printf("Length: %d\n", length(s));
    return 0;
}

The problem is, if you comment out the printf() statement in the length() function, the return statement becomes part of the loop body, and the very first iteration returns from the call and you get the the-then value of i, which is just the entry value for the loop, 0.

for (i = 0; s[i] != '\0'; ++i)
    //printf("%d ", i);           //<-- here
return i;                         // without brace-enfoced scope, this is the loop body.

is the same as

for (i = 0; s[i] != '\0'; ++i)
return i;                                

What You need is the loop to complete the execution, hit the exit criteria and then, execute the return statement with the latest value of i.

So, to avoid the problem, you can enforce empty execution of the loop, by something like

for (i = 0; s[i] != '\0'; ++i) ;   // notice the ; here, ends the scope.
return i; 

or, even better (for the readers)

for (int i = 0; i < 10; i++) 
    {/*nothing here*/}       //indicates empty loop body
return i;

Note: As an alternative way, to enhance the readability, instead of a for construct you can also make use of while loop, which goes like

while (s[i] != '\0') 
{
    i++;                     //increment statement is explicit.
}

Java String length() Method with examples, Java String length() method is used to find out the length of a String. This method of a String. This method counts the number of characters in a String including the white spaces and returns the count. Java String length() method to calculate the length of String without spaces Your email address will not be published. This method returns the length of this string. The length is equal to the number of 16-bit Unicode characters in the string. Syntax. Here is the syntax of this method − public int length() Parameters. Here is the detail of parameters − NA. Return Value. This method returns the the length of the sequence of characters represented by this

In a loop like this:

for (...)
    statement1;
statement2;

statement1 will be the only thing executed in the loop. When you comment out the printf call, return i; is executed on the very first iteration, immediately returning zero.

Notice, however, that statement1 can be empty, so, to run a loop with no body, do:

for (...)
    ; // yes, a hanging semicolon

// or like this:
for (...);

Java - String length() Method, Java - String length() Method - This method returns the length of this string. The length is equal to the number of 16-bit Unicode characters in the string. You can also find string length without strlen function. We create our function to find it. We scan all the characters in the string if the character isn't a null character then increment the counter by one. Once the null character is found the counter equals the length of the string.

If you just commnt out that printf, you will be left with this:

int length(char *s) {
    int i;
    for (i = 0; s[i] != '\0'; ++i)
    return i;
}

This is equal to:

int length(char *s) {
    int i;
    for (i = 0; s[i] != '\0'; ++i){
        return i; // returns in the first iteration, without even incrementing i once
    }
}

Surely this isn't what you intended. Instead, put a semicolon after the for loop:

for (i = 0; s[i] != '\0'; ++i);

This way, for (i = 0; s[i] != '\0'; ++i); won't accidentally affect a following statement.

You can prevent such accidents by adding explicit braces to denote your intention, for instance:

int length(char *s) {
    int i;
    for (i = 0; s[i] != '\0'; ++i) {
        printf("%d ", i);           //<-- here
    }
    return i;
}

Now if you remove the printf line, it doesn't affect the program execution in any other way than omitting the print.

String Length() Method in Java with Example, Return Value: This method returns the length of the string. Java string Length Method Examples: In this program, we have two Strings and we find out  C program to print the length of a String using %n format specifier Construct a string of length L such that each substring of length X has exactly Y distinct letters Minimum length of the sub-string whose characters can be used to form a palindrome of length K

Java String length() method, Java String length() method with method signature and examples of concat, compare, public int length() {; return value.length;; } String str = "Javatpoint";; if(str.length()>0) {; System.out.println("String is not empty Software Testing Tutorial. Python Exercises, Practice and Solution: Write a Python program to calculate the length of a string.

C Program to Find the Length of a String, Calculate Length of String without Using strlen() Function. #include <stdio.h> int main() { char s[] = "Programming is fun"; int i; for (i = 0; s[i] != '\0'; ++i);  Syntax string.length Description. This property returns the number of code units in the string. UTF-16, the string format used by JavaScript, uses a single 16-bit code unit to represent the most common characters, but needs to use two code units for less commonly-used characters, so it's possible for the value returned by length to not match the actual number of characters in the string.

5 Different methods to find length of a string in C++, We say a paragraph'ss length not its size, so length() is to make things more readable. Both string::size and string::length are synonyms and return the exact same value. CPP program to illustrate. // Different methods to find length. // of a string Please write comments if you find anything incorrect, or you want to share  Return Value: It returns an integer which is the length of the string. Below is the Python implementation of the len() method.

Comments
  • That's why you always use brackets {} ^^
  • So what you are saying, if i don't have a semicolon, regardless of how far, the first statement after the loop will get executed. Correct?
  • Here is one situation where while loop should be used instead of for loop where increment Takes place inside the braces.
  • @Michi You mean to say, make the increment of the index explicit by putting it as the loop body for while construct, right?
  • @Sourav Ghosh. Right. :))
  • Even better is to always use explicit braces on loops, conditions etc, then problems like this cannot occur. In perl for example, explicit braces are even mandatory.
  • Good suggestion, I added a version of how the function could look like this way.