Home > Software engineering >  Check If An Array of String Contains Number
Check If An Array of String Contains Number

Time:07-01

I am trying to accomplish a task and pretty close to complete. Here is the scenario - For array of string, I require to sort according to the number of letters in each element as follows:

 string[] str = {"aaa", "cccc", "a"}; 

Output:

a, aaa, cccc //Sorted according to the number of letters

To solve the above, did something as follows that worked:

class Program
{
    static void Main(string[] args)
    {
        int chkNumber;
        string[] str = { "aaa", "cccc", "a",};
        string result = "";

        Array.Sort(str);
        foreach (var i in str)
        {
            bool isNumber = int.TryParse(i, out chkNumber);

            result = String.Join(", ", str.OrderBy(i => i.Length));
        }

        Console.WriteLine(result);
    }
}

But my requirement is to check for a number in the array string and sort as well accordingly. Something as follows:

string[] str = {"aaa", "cccc", "a", "2"};

As it has a number, I tried to check it as follows:

bool isNumber = int.TryParse(i, out chkNumber);

My plan is to get the number and sort it as follows:

a, 2, aaa, cccc //As it's number 2 and places accordingly

Am actually stuck on how to sort that number with the string as well. Is there any efficient to do so or require to change the above code snippet?

CodePudding user response:

It looks like you're trying to sort the array by item length, except for any item that's a number, which should be placed in the corresponding index.

If that's the case, then you could first get all the non-number items, sort them by length, then sort the number items and insert them into their appropriate index.

Things to consider:

  1. What if the number is greater than the number of items in the array?

    • In the code below, if there are fewer items in the array than the number (i.e. no matching index), then I just put the number at the end. You could handle this differently if needed.
  2. What if the number is less than the number of items in the array (i.e. negative)

    • I didn't do anything special to handle negative numbers, so they will end up getting scrambled in with the regular numbers and mess up the results. You can define rules about what to do with them and then apply those rules to the code below. Two that come to my mind are 1) Throw an exception 2) Treat them like non-numbers.
  3. What if there are duplicate numbers?

    • Again, I didn't do anything to handle this. Most likely you would either throw an exception or ignore the duplicates (which will cause the resulting array to shrink in length).

public static string[] CustomSort(string[] input)
{
    if (input == null || input.Length < 2) return input;
    
    // Get all the non-number results sorted by length
    int temp;
    var result = input
                     .Where(i => !int.TryParse(i, out temp))
                     .OrderBy(i => i.Length)
                     .ToList();
    
    // Get all the number results sorted by numeric value
    var numbers = input
                     .Where(i => int.TryParse(i, out temp))
                     .OrderBy(i => int.Parse(i))
                     .ToList();
        
    // Insert each number result into it's correct index
    foreach(var number in numbers)
    {
        var index = int.Parse(number) - 1;
        
        if (result.Count() >= index)
        {
            result.Insert(index, number.ToString());
        }
        else
        {
            result.Add(number.ToString());
        }
    }
    
    return result.ToArray();
}

CodePudding user response:

one simple solution would be:

result = str.OrderBy(i => {
    int num =0;
    if(int.TryParse(i, out num)) return num ;
    return  i.Length;
});
  •  Tags:  
  • c#
  • Related