HereToLearn_
HereToLearn_

Reputation: 1180

Convert string[] to int

I have an array of integers in string form.

string [] TriangleSideLengths

In this array there is going to be 3 int values which represent side length of a triangle. Is there a way from which I can extract individual all 3 values from my array TriangleSideLengths into three int objects like int intSideLengthOne,intSideLengthTwo and intSideLengthThree.

I want to be able to test if these three values actually form a valid triangle?

For instance, entering lengths 10, 10, 100000 wouldn't make it a valid isosceles triangle.

I wanna be able to do this check with the three values stored in my array TriangleSideLengths.

a + b > c
a + c > b
b + c > a

Any help is greatly appreciated. Thanks a lot!! :)

Upvotes: 1

Views: 212

Answers (5)

Bashnia007
Bashnia007

Reputation: 135

int[] sides = new int[TriangleSideLengths.Length];
int counter=0;
foreach(var str in TriangleSideLengths)
{
   int.TryParse(str, out sides[counter++]);
}
if(sides[0] + sides[1] > sides[2]){...}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

You can use LINQ to parse the numbers from the string, like this:

var threeSides = TriangleSideLengths.Select(int.Parse).ToArray();

Here is a demo on ideone.

To do the check, sort the numbers in ascending order, then check that the sum of the first two is strictly greater than the third one:

Array.Sort(threeSides);
if (threeSides[0]+threeSides[1] > threeSides[2]) {
    ...
}

Note that it is not a sufficient condition for the numbers to define a triangle: you must also check that the numbers are strictly positive.

Upvotes: 6

user2702006
user2702006

Reputation: 1

string[] TriangleSideLengths = { "10", "20", "300"};

int[] sides = new int[TriangleSideLengths.Length];

for (int i = 0; i < TriangleSideLengths.Length; i++)    
{       
    sides[i] = int.Parse(TriangleSideLengths[i]);    
}

Upvotes: 0

ismellike
ismellike

Reputation: 629

Try this

string [] TriangleSideLengths = new string[3];
int[] lengths = new int[3];
for(int i = 0; i<=2;i++)
{
 lengths[i]=Convert.ToInt32(TriangleSideLengths[i]);
}
if(lengths[0]+lengths[1]>lengths[2])
   //go crazy

Upvotes: 0

Cignitor
Cignitor

Reputation: 1097

public int toInt(string text)
{
    int tonumber = int.Parse(text);
    return tonumber;
}

Upvotes: -1

Related Questions