devsks's blog

By devsks, 9 years ago, In English

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.

  • Vote: I like it
  • +101
  • Vote: I do not like it

»
9 years ago, # |
Rev. 3   Vote: I like it -46 Vote: I do not like it

Well there are functions like size() and length() if you are using the string 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 takes O(length) time in finding the length of the string but size() function takes only O(log length) time to do it. As you are using char a[100] type of string i think strlen() is the only viable option you have.

  • »
    »
    9 years ago, # ^ |
      Vote: I like it +74 Vote: I do not like it

  • »
    »
    9 years ago, # ^ |
      Vote: I like it +3 Vote: I do not like it

    Are you sure that size() takes O(loglength) time and not O(1)?

    • »
      »
      »
      9 years ago, # ^ |
        Vote: I like it +5 Vote: I do not like it

      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!! :(

    • »
      »
      »
      9 years ago, # ^ |
        Vote: I like it +19 Vote: I do not like it

      Well, O(1) is still :D.