I need to write a function that returns all characters that occur 2 or more times in the text. There isn't any problem when I use it without function (for example on button click). That's how I do it:
for (int i = 0; i < alph.Length; i++) // alph is my text(string)
{
int count = allText.Split(alphCh[i]).Length - 1;
if (count >= 2)
listView2.Items.Add(alphCh[i].ToString());
}
That's how I write function:
public char[] chars2(string text)
{
char[] allChar = text.ToCharArray();
string allText = text.ToString();
string allTextL = text.ToLower();
string alph = "abcdefghijklmnopqrstuvwxyz";
char[] alphCh = alph.ToCharArray();
char[] result = new char[0];
int allcount = 0;
for (int i = 0; i < alph.Length; i++)
{
int count = allText.Split(alphCh[i]).Length - 1;
if (count >= 2)
{
allcount++;
result = new char[allcount];
for (int j = 0; j < allcount; j++)
{
开发者_如何学Python result[j] = alphCh[i];
return result;
}
}
}
return result;
}
But function returns just first character that occurs 2 or more times in the text. For example I write abcbca - func returns a, and I want to func returns a, b, c, to write it into ListView for example. What do I do wrong? Please, I need your help so much. Thanx.
If you have C# 3.0 or newer you can use LINQ:
char[] result = text
.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(g => g.Key)
.ToArray();
Linq can simplify. Does this meet the requirements?
"aabbccpoiu".ToCharArray()
.GroupBy(c => c)
.Where(g => g.Count() > 1)
.Select(g => g.Key)
It returns a, b and c.
Return a List instead, and use it inside the funciton as you do with the listview; just use List<char> rVal = new List<char>();
and then rVal.Add(character)
if its not already added
Also remove the return inside the loop:
Just a suggestion=
public List<char> getMoreThanTwice(string text) {
char[] characters = text.toCharArray();
Dictionary<char, int> chars = new Dictionary<char, int>();
List<char> morethantwice = new List<char>();
for (int i=0;i<characters.Length;i++) {
if (chars.containsKey(characters[i])) {
chars[characters[i]] = chars[characters[i]] + 1;
}else{
chars.Add(characters[i], 1);
}
}
foreach (KeyValuePair keypair in chars) {
if (keypair.Value >= 2) {
morethantwice.Add(keypair.Key);
}
}
return morethantwice;
}
The first return result;
will return directly when it has found the first result.
精彩评论