Why does the code below output this:
"v a" (118,32,97)
"w a" (119,32,97)
"v b" (118,32,98)
"w b" (119,32,98)
"v c" (118,32,99)
"w c" (119,32,99)
and not this (as one would expect if Array.Sort sorted by character
code value):
"v a" (118,32,97)
"v b" (118,32,98)
"v c" (118,32,99)
"w a" (119,32,97)
"w b" (119,32,98)
"w c" (119,32,99)
Is there any way to make Array.Sort sort strings by character code
value?
---------------------------
string[] strings = new string[] {
"w b",
"v a",
"v c",
"w a",
"v b",
"w c"
};
Array.Sort(stri ngs);
PrintStrings(st rings);
private void PrintStrings(st ring[] strings)
{
for (int i=0; i<strings.Lengt h; i++)
{
Console.WriteLi ne(String.Forma t(" \"{0}\" ({1})",
strings[i],
GetASCIICharCod es(strings[i])));
}
}
private string GetASCIICharCod es(string s)
{
StringBuilder sb = new StringBuilder() ;
for (int i=0; i<s.Length; i++)
{
char c = Convert.ToChar( s.Substring(i, 1));
sb.Append(Strin g.Format("{0}{1 }",
((int)c).ToStri ng(),
i<s.Length-1 ? "," : ""));
}
return sb.ToString();
}
Thanks,
Niklas Uhlin
"v a" (118,32,97)
"w a" (119,32,97)
"v b" (118,32,98)
"w b" (119,32,98)
"v c" (118,32,99)
"w c" (119,32,99)
and not this (as one would expect if Array.Sort sorted by character
code value):
"v a" (118,32,97)
"v b" (118,32,98)
"v c" (118,32,99)
"w a" (119,32,97)
"w b" (119,32,98)
"w c" (119,32,99)
Is there any way to make Array.Sort sort strings by character code
value?
---------------------------
string[] strings = new string[] {
"w b",
"v a",
"v c",
"w a",
"v b",
"w c"
};
Array.Sort(stri ngs);
PrintStrings(st rings);
private void PrintStrings(st ring[] strings)
{
for (int i=0; i<strings.Lengt h; i++)
{
Console.WriteLi ne(String.Forma t(" \"{0}\" ({1})",
strings[i],
GetASCIICharCod es(strings[i])));
}
}
private string GetASCIICharCod es(string s)
{
StringBuilder sb = new StringBuilder() ;
for (int i=0; i<s.Length; i++)
{
char c = Convert.ToChar( s.Substring(i, 1));
sb.Append(Strin g.Format("{0}{1 }",
((int)c).ToStri ng(),
i<s.Length-1 ? "," : ""));
}
return sb.ToString();
}
Thanks,
Niklas Uhlin
Comment