Home > Net >  How to out all the int values from a string array and store that int values in another array
How to out all the int values from a string array and store that int values in another array

Time:08-05

There are words and int values in a string array. My goal is to retrieve the int values from another array. I have seen two methods for converting and finding int values from a string array.

To get all the int values from the string, I first create another int array and use an Array.ConvertAll init. The second method is to loop through isDigit().

Now, the problem is that I cannot find a way to store that value in an int array that has been converted to an int. The final goal is to find the minimum and maximum value from the converted values.

string[] strArray1 = { "Bautik", "99", "Sagar", "3", "Tisha", "12", "Riya", "109" };
int result;
int[] num = Array.ConvertAll(strArray1, x =>
{
    bool convertStrIntoInt = int.TryParse(x, out  int result);
    return result;
});

In here, I don't how to get the result outside of it to do a sort to find min and max values.

CodePudding user response:

I don't understand what you want but if you want only int then use this

 List<int> list = new List<int>();
        string[] strArray1 = { "Bautik", "99", "Sagar", "3", "Tisha", "12", "Riya", "109" };
        foreach (string str in strArray1)
        {
            if (int.TryParse(str, out int val))
            {
                list.Add(val);
            }
        }
        int[] vs = list.ToArray();  

now all the int values are stored in vs array, if there are some words which contains the int value and you want them to be extracted you can use regex to find the digits in word also

CodePudding user response:

I'd use LINQ for this:

string[] strArray1 = { "Bautik", "99", "Sagar", "3", "Tisha", "12", "Riya", "109" };

int[] num =
(
    from x in strArray1
    let n = int.TryParse(x, out int n) ? (int?)n : null
    where n.HasValue
    select n.Value
).ToArray();

That outputs:

num

Then you can do this:

int max = num.Max();
int min = num.Min();

CodePudding user response:

Little optimized solution could be something like below

string[] strArray1 = { "Bautik", "99", "Sagar", "3", "Tisha", "12", "Riya", "109" };
var numArray = strArray1.Where(var=> new Regex(@"^\d ").IsMatch(var)).ToArray();
var res = Array.ConvertAll(numArray,s => int.Parse(s));

If we don't want to use Regex can try something like below

string[] strArray1 = { "Bautik", "99", "Sagar", "3", "Tisha", "12", "Riya", "109" };
int testNum;
var numArray = strArray1.Where(var=> int.TryParse(var,out testNum)).ToArray();
var res = Array.ConvertAll(numArray,s => int.Parse(s));

You can then get max and min value using

res.Min(), res.Max()

This should give you a starting point for your problem

CodePudding user response:

You can try Regex like below :

string[] strArray1 = {"Bautik", "99", "Sagar", "3", "Tisha", "12", "Riya", "109"};

int[] num = strArray1.Where(v => Regex.IsMatch(v, @"^\d $")).Select(int.Parse).ToArray();


int min = num.Min();
int max = num.Max();

As you don't want to use Regex, you can go with your solution, just do a small modification to get your desired result. Try this :

string[] strArray1 = { "Bautik", "99", "Sagar", "3", "Tisha", "12", "Riya", "109" };
int[] num = Array.ConvertAll(strArray1, x =>
{
    bool convertStrIntoInt = int.TryParse(x, out int result);
    return result;
}).Where(x => x > 0).ToArray();

int max = num.OrderByDescending(c => c).ToArray()[0];
int min = num.OrderBy(c => c).ToArray()[0];

CodePudding user response:

Here is another way to get int values from a string array into an int array.

Try it on dotnetfiddle.

public static class Extensions
{
    public static int[] ToIntegerArray(this string[] sender)
    {

        var intArray = Array
            .ConvertAll(sender,
                (input) => new {
                    IsInteger = int.TryParse(input, out var integerValue),
                    Value = integerValue
                })
            .Where(result => result.IsInteger)
            .Select(result => result.Value)
            .ToArray();

        return intArray;

    }
}

Use

string[] strArray1 = { "Bautik", "99", "Sagar", "3", "Tisha", "12", "Riya", "109" };
int[] intArray = strArray1.ToIntegerArray();
Array.Sort(intArray);
foreach (var value in intArray)
{
    Console.WriteLine(value);
}

Console.WriteLine($"Min: {intArray.Min()}");
Console.WriteLine($"Max: {intArray.Max()}");

CodePudding user response:

Targeting your intial question:

I don't [know] how to get the result outside of it to do a sort to find min and max values.

You simply can't get a complete solution for your Problem using ConvertAll() with a "normal" int.

So if we take a look at your result:

int[] num = Array.ConvertAll(strArray1, x =>
{
    bool convertStrIntoInt = int.TryParse(x, out int result);
    return result;
});

// num: int[8] { 0, 99, 0, 3, 0, 12, 0, 109 }

We can see each string will result in a 0, since 0 will be returned if the parsing failed - see: Int32.TryParse(...). And therefore it is impossible to differentiate between an real 0 in your input or a string.

But we can tweek the convert a little bit by using Nullable<int>/int?

int?[] num = Array.ConvertAll(strArray1, x =>
{
    return (int?)( int.TryParse(x, out  int result) ? result : null);
});

// num: Nullable<int>[8] { null, 99, null, 3, null, 12, null, 109 }

So with this we are able to differ between a 0 and a string - represented by null.

Now you can perform other operations like num.Max() and num.Min(). If you need an int[] array, you have to run more loops.

int[] num = Array.ConvertAll(strArray1, x =>
{
    return (int?)( int.TryParse(x, out  int result) ? result : null);
}).OfType<int>().ToArray();

//num: int[4] { 99, 3, 12, 109 }

So this is not quite optimal.


My solution for this would be a simple loop.

// Your intput
string[] strArray1 = { "Bautik", "99", "Sagar", "3", "Tisha", "12", "Riya", "109" };

// Output Variables
List<int> result = new();
int min = int.MaxValue; 
int max = int.MinValue;

// Loop
foreach( string item in strArray1)
{ 
    if(int.TryParse(item, out int value))
    { 
        result.Add(value);
        min = min > value ? value : min;
        max = max < value ? value : max;
     }
}

// Output
// result: int[4] { 99, 3, 12, 109 }
// min: 3
// max: 109

As already mentioned by Gian Paolo in the comments of this answer

working with a List<int> is much easier than working with an int[]

..., but if you really need an array, then you can just call ToArray().

int[] resultArray = result.ToArray(); 

Which results in int[4] { 99, 3, 12, 109 }.

  • Related