String manipulation Problem

Discussion in 'C' started by katkat21, Aug 11, 2009.

  1. katkat21

    katkat21 New Member

    Joined:
    Aug 11, 2009
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    student
    Location:
    philippines
    can someone solve my problem

    if the string is college
    the output must be
    c=1
    o=1
    l=2
    e=2
    g=1

    it counts that how many a letter does it used
    thnk you ^^:)
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    I'd probably use an array of 26 ints initialised to zero, then for each letter encountered increment the relevant element. Pseudocode:
    Code:
    int arr[26] initialise to zero
    char *str="college"
    for each character c in str
      arr[str[c]-'a']++
    end for
    for each element e of arr
      if non-zero
        print the letter (e+'a') and the count
      end if
    end for
    
    arr[str[c]-'a']++ is the clever bit: str[c] is a char between 'a' and 'z', and subtracting 'a' from that gives us a number from 0-25 which we use as the index into the array. It may be a good idea to add some limits checking to this, for example if (str[c]>='a' && str[c]<='z') so that you don't accidentally increment something not in the array.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice