0

How to get the string length without using strlen function or counters, like:

scanf("???",&len);
printf("%d",len);

Input: abcde

Expected output: 5

0

4 Answers 4

7

You can use assignment-suppression (character *) and %n which will store the number of characters consumed into an int value:

 int count;
 scanf( "%*s%n", &count );
 printf( "string length: %d\n", count );

Explanation:

%*s will parse a string (up to the first whitespace characters) but will not store it because of the *. Then %n will store the numbers of characters consumed (which is the length of the string parsed) into count.

Please note that %n is not necessarily counted for the return value of scanf():

The C standard says: "Execution of a %n directive does not increment the assignment count returned at the completion of execution" but the Corrigendum seems to contradict this. Probably it is wise not to make any assumptions on the effect of %n conversions on the return value.

quoted from the man page where you will find everything else about scanf() too.

Sign up to request clarification or add additional context in comments.

Comments

3

Use the %n format specifier to get the amount of characters consumed so far and write it to len of type int:

char buf[50];
int len;

if ( scanf("%49s%n", buf, &len) != 1 )
{
     // error routine.
}

printf("%d", len);

Comments

2

You can doing this with the n specifier:

%n returns the number of characters read so far.

char str[20];
int len;
scanf("%s%n", &str, &len);

1 Comment

Thank you for your response. I've just forgotten the %n. The same could also be done with the scanf statement
0

Explanation : Here [] is used as scanset character and ^\n takes input with spaces until the new line encountered. For length calculation of whole string, We can use a flag character in C where nothing is expected from %n, instead, the number of characters consumed thus far from the input is stored through the next pointer, which must be a pointer to int. This is not a conversion, although it can be suppressed with the *flag. Here load the variable pointed by the corresponding argument with a value equal to the number of characters that have been scanned by scanf() before the occurrence of %n.

By using this technique, We can speed up our program at runtime instead of using strlen() or loop of O(n) count.

scanf("%[^\n]%n",str,&len);
printf("%s %i",str,len);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.