Using generics to make an algorithm work on lists of "something" instead of only String's
Posted
by Binary255
on Stack Overflow
See other posts from Stack Overflow
or by Binary255
Published on 2010-04-08T16:26:37Z
Indexed on
2010/04/08
16:33 UTC
Read the original article
Hit count: 353
c#
Hi,
I have a small algorithm which replaces the position of characters in a String:
class Program
{
static void Main(string[] args)
{
String pairSwitchedStr = pairSwitch("some short sentence");
Console.WriteLine(pairSwitchedStr);
Console.ReadKey();
}
private static String pairSwitch(String str)
{
StringBuilder pairSwitchedStringBuilder = new StringBuilder();
for (int position = 0; position + 1 < str.Length; position += 2)
{
pairSwitchedStringBuilder.Append((char)str[position + 1]);
pairSwitchedStringBuilder.Append((char)str[position]);
}
return pairSwitchedStringBuilder.ToString();
}
}
I would like to make it as generic as possible, possibly using Generics. What I'd like to have is something which works with:
- Anything that is built up using a list of instances.
- Including strings, arrays, linked lists
I suspect that the solution must use generics as the algorithm is working on a list of instances of T (there T is ... something). Version of C# isn't of interest, I guess the solution will be nicer if features from C# version >2.0 is used.
© Stack Overflow or respective owner