exercism/csharp/anagram/Anagram.cs

41 lines
1.1 KiB
C#

using System.Collections.Generic;
internal class Anagram {
private string v;
// Anagram is initialized with a string to test other strings against
public Anagram(string v) {
this.v = v.ToLower();
}
// Match takes an array of strings and returns an array that contains
// All anagrams of this.v
public string[] Match(string[] inp) {
List<string> ret = new List<string>();
foreach(string val in inp) {
if(this.v.Length != val.Length) {
continue;
}
string valTest = val.ToLower();
bool isAnagram = true;
if(this.v == valTest) {
continue;
}
for(int i = 0; i < this.v.Length; i++) {
int idx = valTest.IndexOf(this.v[i]);
if(idx == -1) {
isAnagram = false;
}
if(!isAnagram) {
break;
}
valTest = valTest.Substring(0, idx)+valTest.Substring(idx+1);
}
if(isAnagram) {
ret.Add(val);
}
}
return ret.ToArray();
}
}