sort+counting

This is a discussion on sort+counting within the C++ Programming forums, part of the General Programming Boards category; Hi, I have a program that should read a line of text and output the number of words in the ...

  1. #1
    Registered User
    Join Date
    Apr 2003
    Posts
    25

    sort+counting

    Hi, I have a program that should read a line of text and output the number of words in the line and the number of occurrences of each letter. the output of the letters must be in alphabetical order counting both upper and lowercase versions .(ex input: Hello Hi. And the output: there are 2 words
    1 e
    2 h
    1 i
    2 l
    1 o
    I've done the first part but I couldn't solve the second part. first, I changed all the uppercase to lowercase.then,I found this sort but I have the spaces and other punctuations showing with it..
    Code:
     do
     {
       finish = 0;
        for ( i = 0; i < x - 1; i++)      // sorting the string..
        {
          if (s[i] > s[i + 1])
          {
            hold     = s[i];
            s[i]     = s[i + 1];
            s[i + 1] = hold;
    
            finish = 1;
          }
        }
     }while (finish != 0) ;
    * so I decided to delete everything that is not a letter but it didn't work…

    Code:
     for (i=0; i<size; i++)                // string contains only letters..
    	  if (isalpha(s[i]))
    		  temp[i]=s[i] ;
    * and I thought of another way that also didn't work..

    Code:
     for (i=0; i<size; i++)            // string contains only letters..
    	  if (!isalpha(s[i]))
    		  s[i]=s[i+1] ;
    * finally I decided to do the counting any way, but I have the occurrences of each letter repeated as many times as it occurred, as well as ,counting punctuations.

    Code:
     for ( i=0;i<x;i++)                     //counting the occurrences of each letter..
    	{	for(j=0;j<x;j++)
    		{
    			if (s[i]==s[j])
    				a++ ;
    		}
        cout << s[i] << " occured : " <<a << endl;
    	a=0;
    	}
    	cout << endl; 
    	return 0;
    }
    what can i do ??!!

  2. #2
    Cheesy Poofs! PJYelton's Avatar
    Join Date
    Sep 2002
    Location
    Boulder
    Posts
    1,728
    Its real easy to create a function that kills punctuation. Just do something like this:
    Code:
    string killpunc(string s)
    {
       string retString="";
       for (int x=0; x<s.length(); x++)
       {
            if (isalpha(s[x]))
                retString+=s[x]+"";
       }
       return retString;
    }

  3. #3
    Registered User
    Join Date
    May 2003
    Posts
    148
    Another approach
    Code:
    #include <map>
    #include <cctype>
    ...
    std::map<char,int> abc;
    const int size = 100;
    char s[size]
    ....
    for(int i = 0;i < size;++i)
    {
        if(std::isalpha(s[i]))
            abc[std::tolower(s[i])]++;
    }
    
    for(std::map<char,int>::const_iterator iter = abc.begin();iter != abc.end();++iter)
        cout << iter->first << " " << iter->second << endl;

  4. #4
    Cheesy Poofs! PJYelton's Avatar
    Join Date
    Sep 2002
    Location
    Boulder
    Posts
    1,728
    lol, I think that is a little advanced for her

  5. #5
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    you can try to use the asci representation of the characters to identify an index and then increment the value stored at that index. I think it goes something like this:

    char string[800];//string to read
    int array[26] = {0};//array to hold char count all elements set to zero initially

    //loop to read each char in string
    //in loop do something like this:
    if(isalpha[string[i])//count just letters
    {
    tolower(string[i]);//convert to lower case
    array[string[i] - 'a']++;//increment index obtained by substracting the asci value of 'a' from string[i].
    }

    in the end the number of a's will be at index 0, b's at index 1, c's at index 2, etc.
    Last edited by elad; 05-30-2003 at 01:13 PM.

  6. #6
    Registered User
    Join Date
    Apr 2003
    Posts
    25

    didn't get it

    yes i need the program to be simple.we didn't take all the functions!!i know i might sound stupid but what does this mean?

    retString+=s[x]+"";
    how can you make a string=string+char?

    and when i tried it i had an error C2297: '+=' : illegal, right operand has type 'char [1]'
    have a nice day

  7. #7
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Both PJYelton and Wledge's examples use STL. The 'string' class defined in <string> has numerous operators defined for various types. For examples, the + operator will concatenate two strings. Those operators are not similarly defined for cahr and char*s.

    Wledge's is a little more complex, and probably a bit more elegant. The map is an associative container, meaning it has key/value pairs. In this case, the keys are characters, and ints (which count the number of occurences) are the values. An entry is not created until it is accessed, and the map will initialize ints (as values) to 0, which is why this code maintains an accurate count.

    Hope thats a decent explanation.

    Cheers
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  8. #8
    Cheesy Poofs! PJYelton's Avatar
    Join Date
    Sep 2002
    Location
    Boulder
    Posts
    1,728
    Oops, I am so used to using strings that I forget not everybody uses them

    I take it your input is in the form of a char array? I know there is a function that concatenates two char arrays, but without my book I'm not sure exactly what it is. You can just use that in place of my += line and use char arrays instead of strings.

  9. #9
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    From <cstring>
    std::strcat(char*, char*);
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  10. #10
    Registered User
    Join Date
    Apr 2003
    Posts
    25
    ok thanks but isn't there another way??
    have a nice day

  11. #11
    Cheesy Poofs! PJYelton's Avatar
    Join Date
    Sep 2002
    Location
    Boulder
    Posts
    1,728
    To do the whole problem or just kill the punctuation?

  12. #12
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    There are plenty of solutions... What type are you looking for?
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  13. #13
    Registered User
    Join Date
    Apr 2003
    Posts
    25

    Talking anything...

    well...if you know a way to count the number of occurrences of each letter in that string in alphabetical order without the need to kill the punctuations it is ok... but that was the way i was thinking to solve the program...
    have a nice day

  14. #14
    Cheesy Poofs! PJYelton's Avatar
    Join Date
    Sep 2002
    Location
    Boulder
    Posts
    1,728
    Well, personally I wouldn't care about the punctuation. If given the problem I probably would have right off the bat done what elad did.

    Create an int array of size 26, all initialized to zero. This is where you will hold the number of each letter. Spot 0 will be the number of A's, spot 1 will be the number of B's, etc.

    Now go through each letter in the input, if its a non-alpha then skip it and go to the next letter. Whatever letter you are on, increment your int array by one at the corresponding letter. So if you hit the letter Z, then increment array[25] by one. Now, an easy way to do this without having 26 if statements is to simply subtract the letter 'a' from from the current letter. a-a = 0, b-a=1, c-a=2, etc, which happens to be exactly the index in your array you want to increment. So all you need to do is this:
    Code:
    array[s[i]-'a']++;
    So at the end, all you have to do is loop through your array, printing out the amounts of each letter if the value is greater than zero.

    Hope that helps, about as far as I go without writing the entire program for ya

  15. #15
    Registered User
    Join Date
    Mar 2003
    Posts
    72
    I have quick question along the same lines as the original question. What if a person had to count how many times individual letters occurred in a string of text, but did not want to declare it as a char and wanted to use string instead?

    For instance instead of this:

    Code:
    char string[800];//string to read
    int array[26] = {0};//array to hold char count all elements set to zero initially
    
    //loop to read each char in string
    //in loop do something like this:
    if(isalpha[string[i])//count just letters
    {
    tolower(string[i]);//convert to lower case
    array[string[i] - 'a']++;//increment index obtained by substracting the asci value of 'a' from string[i].
    }
    It would be more along the lines of this:

    Code:
    string line;//string to read
    int array[26] = {0};//array to hold char count all elements set to zero initially
    
    cout << "Enter a line of text:\n";
    getline(cin,line);
    //loop to read each char in string
    //in loop do something like this:
    if(isalpha[line[i])//count just letters
    {
    tolower(line[i]);//convert to lower case
    array[line[i] - 'a']++;//increment index obtained by substracting the asci value of 'a' from string[i].
    }
    I am assuming this doesn't work right because of the desire to declare the variable as string instead of char. Is there a way to declare it as string and then perhaps do a static_cast<char> to the variable somewhere else along the line of code so that the same concept could apply? If not, is there a better way that someone could suggest to do it if they wanted (or perhaps were required) to declare the variable as a string instead of char?

    Thanks very much in advance!

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Straight Insertion Sort function problem
    By StaticKyle in forum C++ Programming
    Replies: 6
    Last Post: 05-12-2008, 05:03 AM
  2. threaded merge sort
    By AusTex in forum Linux Programming
    Replies: 4
    Last Post: 05-04-2005, 05:03 AM
  3. Sorting
    By vasanth in forum A Brief History of Cprogramming.com
    Replies: 12
    Last Post: 11-10-2003, 05:21 PM
  4. Can counting sort sort in descending order?
    By Nutshell in forum C Programming
    Replies: 3
    Last Post: 03-06-2003, 09:59 AM
  5. Shell Sort vs Heap Sort vs Quick Sort
    By mackol in forum C Programming
    Replies: 6
    Last Post: 11-22-2002, 08:05 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21