In order to find the numbers of characters in an string we can use scansets in C.
The [%n] format identifier stores the numbers of characters read by the input stream i.e stdin to the given address. Eg:
#include<stdio.h>
int main(void)
{
char st[123];
int len;
scanf("%s%n", st, &len); // total no. of characters will be stored at the address of 'len'
printf("%i", len);
return(0);
}
Output: computer 8
We can also use this identifier to count the numbers of digits of a number etc.
Well there are functions like
size()
andlength()
if you are using thestring
variable , dont forget to include the header file#include <cstring>
or#include <string.h>
. As far as I know strlen() is not used probably because it takesO(length)
time in finding the length of the string butsize()
function takes onlyO(log length)
time to do it. As you are usingchar a[100]
type of string i thinkstrlen()
is the only viable option you have.Are you sure that
size()
takes O(log length) time and not O(1)?Indeed size() and length() take O(1) time. That was my mistake but i dont know why i aint able to edit or delete my post!! Thats why i didnt change it and the negative feedback was another factor for not changing it!! :(
Well, O(1) is still :D.