About C# regarding string
1) How can i count the repetition of word in a string in c#2)How can i count the repetition of a character in string in c#
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace ConsoleApplication16
{
class Program
{
static readonly string[] Tests = { "abcdabcd", "xabcdabcd", "abcdabc", "xaaabcdabcd" };
static readonly Regex FindDup = new Regex(@"(.+)\1", RegexOptions.IgnoreCase);
static void Main(string[] args)
{
foreach (string t in Tests)
{
MatchCollection allMatches = FindDup.Matches(t);
Trace.WriteLine(string.Format("{0}: {1}", t, allMatches.Count));
}
}
}
}
//output
abcdabcd: 1
xabcdabcd: 1
abcdabc: 0
xaaabcdabcd: 2
using System.Linq;
string szInputStr = "hello friend, its a demo to find occurence of characters";
char cSearchChar = 'r';
int iFinalCharCount = szInputStr.Where(chVar => chVar == cSearchChar).Count();
Console.WriteLine("Repetition of a character '" + cSearchChar + "' in string: " + iFinalCharCount);
string[] szArrInput = szInputStr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string szSearchStr = "demo";
var iFinalWordCount = (from eachWord in szArrInput
where eachWord.ToUpperInvariant() == szSearchStr.ToUpperInvariant()
select eachWord).Count();
Console.WriteLine("Repetition of word '" + szSearchStr + "' in a string: " + iFinalWordCount);
string MyText = "This is my test in the test appliction";
string FindString = "test";
// Loop through all instances of the string 'text'.
int count = 0;
int i = 0;
while ((i = MyText.IndexOf(FindString , i)) != -1)
{
i += FindString .Length;
count++;
}
Console.WriteLine(count.tosString());
//Character
string st = "India is Big Country";
int cnt = 0;
for (int i = 0; i <= st.Count() - 1; i++)
{
if (st[i].ToString() == "I")
{
cnt = cnt + st[i];
}
}
//Word
string st1 = "India is Big Country";
int cnt1 = 0;
for (int i = 0; i <= st1.ToString().Split(' ').Count() - 1; i++)
{
if (st1[i].ToString() == "India")
{
cnt1 = cnt1 + st1[i];
}
}
string title = "Dotnetspider is code based";
CharEnumerator chEnum = title.GetEnumerator();
int ctr = 1;
string outputLine1 = null;
string outputLine2 = null;
string outputLine3 = null;
while (chEnum.MoveNext())
{
outputLine1 += ctr < 10 || ctr % 10 != 0 ? " " : (ctr / 10) + " ";
outputLine2 += (ctr % 10) + " ";
outputLine3 += chEnum.Current + " ";
ctr++;
}