8

I have a list of string, which is most likely, but not guaranteed to contain a list of numerics, i.e.,

{"1", "6", "2", "21", "89"}

What is the way to sort the string list so that it will always appear in ascending order?

I can't parse the string to numeric first before doing the sorting simply because the string can contain non numeric characters. And I don't want to go through the list and check-cast each component to numerics and do the sorting. Is there already a library existing out there for this purpose?

In the case where we have mix numerics and non-numeric string item, numeric strings always take precedence over the non numeric ones.

1
  • 1
    The phrase you're looking for is "natural order sort". Commented Feb 8, 2010 at 15:41

3 Answers 3

8

This has been asked before slightly differently, but the same answer still applies, as they have a C# implementation on the same site.

SO Question: Sort on a string that may contain a number

Answer provided by ScArcher2: The Alphanum Algorithm

Sign up to request clarification or add additional context in comments.

Comments

1

You want to sort elements, just like Windows XP Explorer does with files. See this article on how to do this.

Comments

0

If this is C#, that's what Int32.TryParse() is for.

If this is C++, then std::string::find_first_not_of is a decent bet. Pass it a string containing the ascii chars for the digits 0 to 9 (plus the minus and plus signs?) and if it returns -1 then it is an integer.

1 Comment

Nope, he want to be able to sort lists like this one: { a1, a10, a11, a2, a3 } in a natural way: { a1, a2, a3, a10, a11 }. TryParse will obviously not work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.