Monday, May 14, 2007

Method to sort an array of strings in descending order of number of words in each array element

Just adding a method which i wrote for an application for which the requirement was scrapped.
Hope someone can refer to this silly method. ;)

///
/// Method to sort an array of strings in descending order of number of words in each array element
///

/// Array to be sorted
/// Array sorted in descending order of number of words in each array element

private static string[] SortArrayWithDescendingWordCount(string[] strArray)
{
//Array to store the number of words in each string of the array to be sorted
int[] wordLengths = new int[strArray.Length];
//variable to keep track of array index of wordLengths array.
int arrayIndex = 0;
foreach (string str in strArray)
{
//split the string in to an array of words and store the word count in wordLengths array.
wordLengths[arrayIndex] = str.Split(' ').Length; ;
arrayIndex++;
}
//Sort arrays(ascending order) by taking wordLenths array as key and strArray as value
Array.Sort(wordLengths, strArray);
//now reverse strArray array to sort the array in descending order of number of words in each array element
Array.Reverse(strArray);
return strArray;
}

No comments: