Click here to Skip to main content
16,008,942 members
Please Sign up or sign in to vote.
2.23/5 (4 votes)
See more:
I need a help for a program in c#. What is the best optimized way to write a program that accepts string from user dynamically, tokenize it , find the occurances of only c# reserve words and give the count of the keywords in sorted manner.

Ex if my string is

" I am new to programming. I need a class example. Any new sample is okay. I am giving new so that it is repeated again"

Program should find that there are reserved words used like "Class and new"

My output should be ( Keyword and count in sorted way )

new - 3
class - 2.

Please help :)

additional information copied from comment below
I even tried this and wrote an algorithm as follows

1. Take an array that has the list of all reserve words in c#
2. Take a user input for string to be checked for keywords from the user
3. split the user text using regular expression ( check for space or comma or ... )
4. now we have the individual tokens of the user provided input
5. Now group the tokens and have their count
5. Now we need to iterate through tokens and for each keyword found print the element along with count.

I am not sure whether this is the optimized way to do it. Please let me know if anything needs to be corrected in the logic

Based on the above algorithm I codes as below

C#
class CountKeyWords
{
    static void Main()
    {
        var myListOfKeywords = new [] {struct, public, class, ...};
        string userInput;

        Console.WriteLine("Enter one or more lines of text (press CTRL+Z to exit)");
        Console.WriteLine();
        do
        {
            userInput = Console.ReadLine();

        } while (userInput!= null);

        // An enumerable collection, not in memory yet.

        var keywordCount = from keyword in userInput.Split(new []{" ","(", ...}) 
                           group by keyword into g
                           where myListOfKeywords.Contains(g.Key)
                           select new {g.Key, g.Count()}

    foreach(var element in keywordCount)
    Console.WriteLine(String.Format("Keyword: {0}, Count: {1}", element.Key, element.Count));
    } // End of Main()
}// End of class CountKeyWords

Let me know if this logic is good?
Posted
Updated 28-Dec-13 9:20am
v5
Comments
BillWoodruff 27-Dec-13 19:20pm    
Writing out the algorithm is a good first step ! Now, how about showing some of the code you have written, and asking specific questions about it ? People here will be happy to help you improve it, or deal with problems, give you ideas.
Member 10491035 28-Dec-13 12:25pm    
I posted the code for the algorithm above...Can anyone please check and let me know if it is correct and optimized or not?

1 solution

This is not how CP usually works. Most important goal here is to learn and help learning.
You are supposed to try it on your own, and come here when you got stuck with something, with a concrete question about your code, design, etc.
Please have a look to What have you tried?[^] to see a good explanation about what I mean.
Don't forget people here don't get payed. And besides, if we give you a ready-to-go solution, it is not going to help you because you are not going to learn anything from it.

EDIT (after comment of the algorithm):
I would say there are several points that could be important to choose the best solution. Example: the possible (max) lenght of the input string.

Considering the example you have given, I think it can be done easier.
- Take the array with the list of all reserved words in c#
- Iteration to go through the array, using IndexOf (link_1[^], link_2[^]) to check if the current reserved word is in the string.
If found: move to that index, counter++ and execute IndexOf again
If not: check next word

In other words, with an iteration within the other iteration it could be enough

I hope you understand what I mean
 
Share this answer
 
v4
Comments
Member 10491035 27-Dec-13 19:07pm    
Hi Nelek,

I even tried this and wrote an algorithm as follows

1. Take an array that has the list of all reserve words in c#
2. Take a user input for string to be checked for keywords from the user
3. split the user text using regular expression ( check for space or comma or ... )
4. now we have the individual tokens of the user provided input
5. Now group the tokens and have their count
5. Now we need to iterate through tokens and for each keyword found print the element along with count.

I am not sure whether this is the optimized way to do it. Please let me know if anything needs to be corrected in the logic
Sergey Alexandrovich Kryukov 27-Dec-13 22:34pm    
Bill, I have to disagree with you. Why would you disqualify Nelek for playing judge-and-jury role in relation to OP, but at the same time qualify yourself to play the same role in relation to Nelek? Don't you see at least something illogical in it?

Maybe this answer is not optimal for the situation, but at least Nelek has given some really useful practical advice: how to approach learning, including the use of CodeProject, and, ultimately, how to approach this problem with arrays, etc.

That "What have you tried" link is really useful and instructive. I often use it in comments, but I leave it in comments when I have nothing else to add. The idea of importance of learning is also valuable, even if it may seem somewhat trivial. OP really need it.

After all, the boundary between legitimate answer and answer which should better be a comment is quite blurry, and our opinions on this can be different. I would suggest using such criteria as "interesting" and "useful", whichever can qualify the answer, and be somewhat tolerable to answers which seem to be close to this boundary. Sometimes even just a joke can be worth posting as an answer, if it good and has some wisdom in it. Russians say: "Tale is a lie, but with a hint in it, a lesson for good fellows"... Again, maybe this answer could be better, but it does have such a lesson in it; so I voted 5.

I know that sometimes you can be tough to those who post answers, and I admit that this can be for quite a good reason, but I think in this very case there is something you could think at. If you pointed out some real flaw in the post, except this just emotional "judqe-and-jury" thing, it would be a different story.

Cheers,
—SA
BillWoodruff 27-Dec-13 23:41pm    
Sergey, my down-vote was because of the accusatory tone and character defaming language in the original content of the response, coupled with the addition negative tags in the title of the OP's question.

Since Nelek has modifed his post, and removed that content, I have retracted my comment, and changed my vote to a neutral #3 ...

I would never down-vote a "solution" for being general advice ... alone ... even though I do believe that the quality of CodeProject QA is diminished by the frequency of such "sermons" entered as "solutions."

I will vigorously protest the actions of anyone who uses CodeProject to gratuitously insult other people, particularly those who may be from countries where English is not their "mother tongue."
Sergey Alexandrovich Kryukov 27-Dec-13 23:53pm    
Just for your information: #3 counts like down-vote (points are subtracted), but perhaps this is not so important.
Frankly, I did not find anything "accusatory", but it was just criticism, and motivated criticism is a very good thing, it should never be "punished", if we want to remain objective and constructive. I still think the answer was useful.

I did not interfere in your other attack on Nelek's answer, just to avoid adding unnecessary noise to the discussion, but in that case the answer was much better, and Nelek's answer was less instructive. This answer was fine, you just don't want to admit it.

It's your decision, but I just suggest you think about your judgement. I would hate if we run into the war against certain styles of answers, while from time to time we face posts where some members simply tell us bad words as personal characteristic and not always pay for such behavior. It would be much better to set examples of better answers by actually posting better answers...

—SA
Sergey Alexandrovich Kryukov 28-Dec-13 0:01am    
One short note on "mother tongue": it is apparent that really bad wording is often the result not of bad language knowledge, but pure laziness, because all of us, say, can write texts under the spell checker. If some 50% of words are not known English words but words like "perticular", "implimentation" or worse, this is not poor knowledge, this is just rudeness, laziness, disrespect. Languages are eroded by sloppy usage, and this is sad...
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900