473,664 Members | 2,770 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Find # of Occurences & count in string using Collections/Generics

3 New Member
Hi,

I tried so much working with this to get distinct Words and their count. I'm using ASP.NET 2.0.
And i also googled so much. I need HELP from anyone to get the required output.

1)Ex(String): The DOTNET is Very Cool! The Best.
2) Capture all the sequences like Spaces, Fullstops, Question Marks, Exclamations, Apostrophes, New Lines....(May be with RegEx?)
3)Split Words According to the above sequences
4)Get Distinct Words(Occurrenc es) and their count based on the input string in 1st statement.

Desired O/P:

The - 2
DOTNET - 1
Is - 1
Very - 1
Cool - 1
Best - 1


My Sample Code is as follows

ASPX:
Expand|Select|Wrap|Line Numbers
  1. <asp:TextBox ID="txtString" runat="server" TextMode="MultiLine" Height="100px" Width="500px"></asp:TextBox>
  2. <asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" />
  3.  
CS:
Expand|Select|Wrap|Line Numbers
  1. //Is it possible with Dictionary
  2. SortedList<int, string> sl = new SortedList<int, string>();
  3.  
  4. protected void btnSubmit_Click(object sender, EventArgs e)
  5. {
  6. //Here i'ld like to check for Space, Question Mark, New Line, Exclamation, Apostrophe,.....
  7. //Now i'm checking only for spaces. I need the above sequences loop also.
  8. string[] Words = txtString.Text.Split(' ');//Space Split
  9. for (int i = 0; i < Words.Length; i++)
  10. {
  11. sl.Add(i, Words[i]);
  12. }
  13.  
  14. foreach (KeyValuePair<int, string> kvp in sl)
  15. {
  16. //I want to print Distinct Words and their Count
  17. Response.Write(kvp.Value + " " + kvp.Key + "<br />");
  18. }
  19. }
  20.  
Mar 4 '10 #1
2 3546
PRR
750 Recognized Expert Contributor
Try this:
Expand|Select|Wrap|Line Numbers
  1.  
  2. public static void WordsinString(string str)
  3.         {
  4.             char[] sep = new char[] { ' ' };
  5.             Dictionary<string,int> strCount=new Dictionary<string,int>();
  6.  
  7.             string[] temp = str.Split(sep,StringSplitOptions.RemoveEmptyEntries);//, StringSplitOptions.RemoveEmptyEntries);
  8.  
  9.  
  10.             foreach (string s in temp)
  11.             {
  12.                 //Console.WriteLine(s);                
  13.  
  14.                 if (strCount.ContainsKey(s))
  15.                 {
  16.                     strCount[s] = (int)strCount[s] + 1;
  17.                 }
  18.  
  19.                 else
  20.                 {
  21.                     strCount.Add(s,1);
  22.                 }
  23.  
  24.  
  25.             }
  26.  
  27.             foreach (KeyValuePair<string, int> p in strCount)
  28.             {
  29.                 Console.WriteLine(p.Key+"  "+ p.Value);
  30.             }
  31.  
  32.  
  33.         }
  34.  
or
Expand|Select|Wrap|Line Numbers
  1. public static void WordsInString(string str)
  2.         {
  3.             string[] temp = str.Split(new char[] { ' '}, StringSplitOptions.RemoveEmptyEntries);
  4.  
  5.             Dictionary<string, int> strCount = new Dictionary<string, int>();
  6.  
  7.             Regex rgx; //= new Regex(pat, RegexOptions.IgnoreCase);
  8.             MatchCollection matches ;//= rgx.Matches(str);
  9.  
  10.             foreach (string s in temp)
  11.             {
  12.                 rgx=new Regex(s, RegexOptions.IgnoreCase);
  13.  
  14.                 matches = rgx.Matches(str);
  15.  
  16.                 if (!strCount.ContainsKey(s))
  17.                 {
  18.                     strCount.Add(s, matches.Count);
  19.                 }               
  20.  
  21.  
  22.             }
  23.  
  24.             foreach (KeyValuePair<string, int> p in strCount)
  25.             {
  26.                 Console.WriteLine(p.Key + "  " + p.Value);
  27.             }
  28.  
  29.         }
  30.  
Mar 4 '10 #2
DexterID
3 New Member
char[] sep = new char[] { ' ', '.', '?', '!', '\n', '\r',',' };
worked perfectly. Thanks.
I/P:
the the.the?the!the
the,
O/P:
the 6

Thanks a lot PRR.
Thanks for ur Dexterity.
Mar 4 '10 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

4
1820
by: Madestro | last post by:
Hi guys, I am making a small program to retrieve e-mails from POP accounts. I got all the e-mail parsing stuff figured out, but I cannot seem to come up with a way to find out which e-mails are NEW so I don't have to retrieve them all. If you have experience with this kind of thing, you know that the server creates unique IDs for all the messages, but this IDs are not guaranteed to be unique, since they can be reused once a message is...
2
2092
by: Niklas E | last post by:
Does anyone know how to get all nodes in a xml-document that start with a certain text? In my case I want to count all suppliers ( <id>Supplier*</id> ) <root> <customer> <name>ABC</name> <id>Supplier123</id> </customer>
4
13637
by: Jason Gleason | last post by:
What's the most efficient way to get the number of occurences of a certain string in another string..for instance i'm using the following code right now... private int CharacterCounter(String text,String Character) { int count = 0;
3
3166
by: Poewood | last post by:
Okay here are four classes for a pocket pc program: Input, fpositional, ComboBoxArray and TextBoxArray. The "input" class is the form. I use the fpositional class to handle most of the functions for the objects on the form, in addition the The objects are created in the fpositional class and affixed to the Input form through the fpositional constructor which takes the form as an argument. The ComboBox and TextBox Array classes hold the...
2
15928
by: ESPNSTI | last post by:
Hi, I'm trying to use a generics dictionary with a key class that implements and needs IComparable<>. However when I attempt to use the dictionary, it doesn't appear to use the IComparable<> to find the key. In the example below, accessing the dictionary by using the exact key object that was used to add to the dictionary works. (see code comment 1). However, if I attempt to access the dictionary by using a key object that
1
6414
by: ratnakarp | last post by:
Hi, I have a search text box. The user enters the value in the text box and click on enter button. In code behind on button click i'm writing the code to get the values from the database and binding it to a repeater control. This repeater control has multiple text boxes and buttons. Can you please tell me how can i do paging in this case ? I'm posting my code below. The problem is that if i click on "AdjustThisAd" button, it opens...
1
3858
by: John_H | last post by:
Re: ASP.NET 2.0 I would like suggestions or code examples on how to collect a variable length list of input data (item# & item quantity specifically). I thought that I could accomplish this using a GridView that has ViewState enabled, an ObjectDataSource to process the submitted list, textboxes for getting new item data and an add button. Does this approach sound feasible or are there better alternatives? My problem is that I don't...
14
2583
by: Jerad Rose | last post by:
I'm relatively new to C# and polymorphism, so what I'm trying to accomplish may not be possible, or there may be a totally different approach that I should be taking. I have a base class (MyBase) and a collection of MyBase objects (MyBaseCollection). Now, I also have an extension to MyBase (MyExtendedBase : MyBase) that has additional properties. And lastly, I have a collection of MyExtendedBase objects(MyExtendedBaseCollection :...
4
3369
by: Dameon | last post by:
Hi All, I have a process where I'd like to search the contents of a file(in a dir) for all occurences (or the count of) of a given string. My goal is to focus more on performance, as some of the files could be upwards of 25mb in size and time is important. I don't want to take the route of loading the text of the file into a giant string and searching it, but would rather focus on a performance-minded solution. Any sugesstions for a...
18
3865
by: Neehar | last post by:
Hello For one of the interviews I took recently, I was given an offline programming quiz. In 30 minutes I had to write code in C++ to counts the number of times each unique word appears in a given file. I tried my level best even after the quiz to come up with a solution but cudnt find an efficient one. :( This is what I did.
0
8348
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8863
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8779
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8636
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7376
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6187
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
2765
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2004
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1761
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.