Coding Challenge - ASP.NET Program : Count number of occurrences in a given string with additional criteria - StringComparison.InvariantCultureIgnoreCase
Write a ASP.NET with C# program to achieve the following
Given a sentence, count each word for number of occurrences (Main Criteria: No repetition)
Additional Criteria
Given a sentence, count each word for number of occurrences (Main Criteria: No repetition)
Additional Criteria
- Case should be ignored
- Comma should not be counted
- An extra space more than single space should be ignored
CountWord.aspx.cs
<div>
<table>
<tr>
<td>Enter the string
</td>
<td>
<asp:TextBox ID="txtInputString" Width="500px" runat="server">
</asp:TextBox>
</td>
<td>
<asp:Button ID="btnShowResult" runat="server" OnClick="btnShowResult_Click" Text="Click for result" />
</td>
</tr>
<tr>
<td>The result is
</td>
<td>
<asp:Label ID="lblResult" runat="server"></asp:Label>
</td>
<td>
</td>
</tr>
</table>
</div>
CountWord.aspx
protected void btnShowResult_Click(object sender, EventArgs e)
{
string givenString =
txtInputString.Text.Trim();
StringBuilder StrResult = new StringBuilder();
List<string> Str1 =
givenString.Split(' ').ToList();
Hashtable HtUniqeString = new Hashtable();
foreach (string SingleStr1 in Str1)
{
if
(SingleStr1.Trim() != string.Empty)// Excluding any extra spaces
{
string TempString = SingleStr1.Replace(',', ' ');// Remoce any commas
if (!HtUniqeString.ContainsKey(TempString.Trim()))
{
HtUniqeString.Add(SingleStr1, "");
}
}
}
foreach (DictionaryEntry DictEntry in HtUniqeString)
{
int
Count = 0;
foreach (string SingleStr1 in Str1)
{
// Compare the strings irrespective of
case
if (SingleStr1.Equals(DictEntry.Key.ToString(), StringComparison.InvariantCultureIgnoreCase))
Count++;
}
string Time = "Time";
if
(Count > 1) Time = "Times";
StrResult.AppendLine("'" + DictEntry.Key.ToString() +
"' has
occured "
+ Count.ToString() + " "
+ Time + " ,");
}
lblResult.Text = StrResult.ToString();
a
}
Comments