Thread: strspn problems with '#' character.

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Dec 2017
    Posts
    1,642
    strcspn does what you want. The 'c' stands for compliment, and it counts how many leading characters of your string are not any of the given characters. It returns the length of the string if none of the given characters are in the string.
    Code:
        size_t n = strcspn(argv[1], "#");
        if (n < strlen(argv[1]))
            printf("First # is at position %zu\n", n);  // %zu is correct for size_t
        else
            printf("# is not in the string\n");
    You could also use strchr and subtract the original string start from the result (if not NULL).
    A little inaccuracy saves tons of explanation. - H.H. Munro

  2. #2
    Registered User
    Join Date
    Apr 2019
    Posts
    121
    Quote Originally Posted by john.c View Post
    strcspn does what you want. The 'c' stands for compliment, and it counts how many leading characters of your string are not any of the given characters. It returns the length of the string if none of the given characters are in the string.
    Code:
        size_t n = strcspn(argv[1], "#");
        if (n < strlen(argv[1]))
            printf("First # is at position %zu\n", n);  // %zu is correct for size_t
        else
            printf("# is not in the string\n");
    You could also use strchr and subtract the original string start from the result (if not NULL).
    Ty, I will look into these.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 04-01-2016, 11:22 AM
  2. Problems reading in character
    By jjohan in forum C Programming
    Replies: 8
    Last Post: 09-11-2014, 01:45 AM
  3. Problems with character input
    By OmnipotentCow in forum C Programming
    Replies: 19
    Last Post: 06-20-2003, 03:39 PM
  4. strspn()
    By JDMac in forum C Programming
    Replies: 4
    Last Post: 11-04-2002, 04:01 PM
  5. int StrSpn(char *str, int ch);
    By Krush in forum C Programming
    Replies: 5
    Last Post: 11-01-2002, 07:13 PM

Tags for this Thread