C string length without using strlen() | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

C string length without using strlen()

#include <stdio.h> int main() { char s[10]; int i; printf("Enter a string: "); scanf("%s", s); for(i = 0; s[i] != '\0'; ++i); printf("Length of string: %d", i); return 0; } If i/p: “ i a m” I want o/p: 6 How can i modify it

29th Apr 2020, 6:59 PM
Haritha Vuppula
Haritha Vuppula - avatar
11 Answers
+ 4
The issue your having is with the scanf...If you really need to use it try this (Honfu posted this method a few months back).:- #include <stdio.h> int main(){ char s[10]; printf("Enter a string: "); scanf("%[^\n]s", s); int i = 0; while(s[i]) i++; printf("Length of string: %d", i); return 0; }
29th Apr 2020, 9:06 PM
rodwynnejones
rodwynnejones - avatar
+ 4
Haritha 79 Try this code it's working properly but shows some warning ignore that.👍👍 Code: #include <stdio.h> #include <string.h> int main() { char s[10]; int i; printf("Enter a string: "); gets(s); puts(s); for(i=0; s[i]; i++); printf("Length of string: %d", i); return 0; }
29th Apr 2020, 8:02 PM
! Bad Coder
! Bad Coder - avatar
+ 1
! Bad Coder thnq😀
29th Apr 2020, 8:06 PM
Haritha Vuppula
Haritha Vuppula - avatar
0
Modify it how? What exactly is your problem/question?
29th Apr 2020, 7:19 PM
HonFu
HonFu - avatar
0
Create an int counter, in for loop increase it by 1. After for loop is complete add 1 again for null terminator.
29th Apr 2020, 7:56 PM
Mustafa K.
Mustafa K. - avatar
0
loop condition??
29th Apr 2020, 7:58 PM
Haritha Vuppula
Haritha Vuppula - avatar
0
how to add 1?? i didnt understand why to add again
29th Apr 2020, 8:01 PM
Haritha Vuppula
Haritha Vuppula - avatar
0
can u send u code if there is no condition then for loop repeats?
29th Apr 2020, 8:03 PM
Haritha Vuppula
Haritha Vuppula - avatar
0
Mustafa K. thnk you i got it😊
29th Apr 2020, 8:08 PM
Haritha Vuppula
Haritha Vuppula - avatar
0
Haritha 79 For loop repeats till the last index of string after that it breaks.
29th Apr 2020, 8:08 PM
! Bad Coder
! Bad Coder - avatar
0
Haritha 79 ur welcome 👍
29th Apr 2020, 8:09 PM
! Bad Coder
! Bad Coder - avatar