Extracting char from string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Cyka
    New Member
    • Sep 2008
    • 1

    Extracting char from string

    Need to prompt user for text, count occurrence of each alphabetic character, then sort and print in descending order. I'm using two parallel arrays, one for characters, one for occurrence of each, I know how to sort with a for loop. Don't know how to extract from string.

    Use something like
    while (cin >> s)
    ?

    Any suggestions?

    Program needs to read text until terminated by pressing <enter><ctrl+d> . This is all in a Unix environment, code is C++, if it matters.
  • boxfish
    Recognized Expert Contributor
    • Mar 2008
    • 469

    #2
    You can use the indexing operator, []. myString[i] will give you the character in myString at position i; is this what you're looking for?
    For example:
    Code:
    string myString = "byeworld";
    cout << myString[0] << endl; // Prints out b.
    cout << myString[1] << endl; // Prints out y.
    Or do you already know this and are trying to do something else?

    Comment

    • gpraghuram
      Recognized Expert Top Contributor
      • Mar 2007
      • 1275

      #3
      You can get the C string from the string using .c_str() and then work on it as a normal C string.

      Raghu

      Comment

      • Ganon11
        Recognized Expert Specialist
        • Oct 2006
        • 3651

        #4
        Are you allowed to use a map? This sort of task would work very well for a map.

        Alternatively, you could find a way to use only one array to maintain the count of each letter. You'd have to use the array indexes to indicate which letter you had, though.

        Comment

        • weaknessforcats
          Recognized Expert Expert
          • Mar 2007
          • 9214

          #5
          Originally posted by Cyka
          Don't know how to extract from string.
          You don't need to do this.

          I asume your array of counts has been initialized to 0.

          All you have to do this look at each character of the string and add 1 to the correct count.

          Comment

          Working...