Home > Software design >  I don't know why length is 1 than real in textfile
I don't know why length is 1 than real in textfile

Time:05-21

The following code check the longest word in a string.

char *fp2 = strtok(str, " .");

if (fp2 == NULL) {
    if(strlen(str) >= length) {
        length = strlen(str);
    }
}  else if (fp2 != NULL) {
    while (fp2 != NULL) {
        if (strlen(fp2) >= length) {
            length = strlen(fp2);
        }
        fp2 = strtok(NULL, " .");
    }
}

str is textfile and the length is variable.

but if textfile is like this "aa\na " it release 3 not 2.

Why is this release 1 than real? I don't know.....

CodePudding user response:

the asnwer should be 4

 "aa\na a"
  12 34

this code

int main() {
    char str[] = "aa\na a";
    char* fp2 = strtok(str, " .");
    int length = 0;
    if (fp2 == NULL) {
        if (strlen(str) >= length) {
            length = strlen(str);
        }
    }
    else if (fp2 != NULL) {
        while (fp2 != NULL) {
            if (strlen(fp2) >= length) {
                length = strlen(fp2);
            }
            fp2 = strtok(NULL, " .");
        }
    }
    printf("length = %d\n", length);
}

produces

length = 4

CodePudding user response:

For starters the if statement is redundant. If the string str does not contain any character except the characters specified as delimiters then you will get in any case the value of length equal to 0 without using the if statement.

if (fp2 == NULL) {
    if(strlen(str) >= length) {
        length = strlen(str);
    }

That is the string does not contain a word.

Also in this if statement

    if (strlen(fp2) >= length) {

it is better to use the operator > instead of the operator >=

    if (strlen(fp2) > length) {

And you should avoid redundant calls of strlen.

The code can look simpler as for example the following way

size_t length = 0;
char *fp2 = strtok(str, " .");

while (fp2 != NULL) {
    size_t n = strlen( fp2 );  
    if ( length  < n ) {
        length = n;
    }
    fp2 = strtok(NULL, " .");
}

For the string looked like "aa\na " the maximum substring contains 4 characters "aa\na". To exclude the new line character '\n' you need to include it in the set of delimiters.

In general it is much better to use functions strspn and strcspn instead of strtok without changing the source string.

  • Related