0

Im reading file line by line and i want to convert some value to integer. One of the line of file is 92.44.12.5/28 and i want to convert 5 to integer. Im able to convert until the 12 but it didnt convert to 5 .

string[] ip1 = line.Split('.');
int [] ipArray = Array.ConvertAll(ip1[2].Split(),Int32.Parse);

what is wrong with my code?

user3297904
  • 59
  • 2
  • 8
  • 2
    You split by '.', but after the last '.' you have "5/28", which isn't an integer. – waka Feb 12 '14 at 12:22

8 Answers8

5

You can use LINQ + int.Parse:

int[] ipArray = lines
    .Select(l => int.Parse(l.Split('/')[0].Split('.').Last())); 
    .ToArray(); 

This presumes that the format is strict, otherwise you get an exception at int.Parse.

Here's a safer version:

int ip = 0;
int[] ipArray = lines
    .Where(l => l.Contains('/') && l.Contains('.'))
    .Select(l => l.Trim().Split('/')[0].Split('.').Last())
    .Where(i => int.TryParse(i, out ip))
    .Select(i => ip)
    .ToArray(); 

If you instead want to find all 4 numbers of all IP's, so one array for every line:

int[][] allIPs = lines
    .Where(l => l.Contains('/') && l.Contains('.'))
    .Select(l => l.Trim().Split('/')[0].Split('.'))
    .Where(split => split.Length == 4 && split.All(str => str.All(Char.IsDigit)))
    .Select(split => Array.ConvertAll(split, int.Parse))
    .ToArray(); 

Note that this is not IPv6 compatible ;)

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • I'm sorry If I'm not getting something here, but will this compile ? I'm under the assumption that `lines` is a `string` meaning -> `.Select(l =>` will get you a char (can't call `.Split()`). – Dimitar Dimitrov Feb 12 '14 at 12:30
  • @DimitarDimitrov: but OP stated that he is reading a file line by line. The `line.Split` is just an excerpt. So replace my `lines` with `File.ReadLines(path)`. – Tim Schmelter Feb 12 '14 at 12:32
  • He's saying "a line", but anyway, I see what you're saying, my bad :) +1 – Dimitar Dimitrov Feb 12 '14 at 12:36
  • 1
    @GrantWinney: actually i'm not using this approach myself often because i'm feeling a little bit uncomfortable by using a local variable in this way since this is an undocumented behaviour which might change in future versions of the framework(although very unlikely). Mostly i use either the `All(Char.IsDigit)` for a `int`-precheck (my second example above) or a custom extension method that returns a `Nullable` as you can see here. http://stackoverflow.com/a/16613455/284240 – Tim Schmelter Feb 12 '14 at 12:55
1

A simplest fix for your code is (this will convert all your literals):

string[] ip1 = "92.44.12.5/28".Split('.', '/');
int [] ipArray = Array.ConvertAll(ip1,Int32.Parse);

Console.WriteLine(ipArray[3]);
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
0

Use that:

line.Split(new char[] { '.', '/' });
toATwork
  • 1,335
  • 16
  • 34
0

line.Split('.') converts your string into an array containing the following elements: 92, 44, 12, 5/28. The first three will work fine, but not the last one; 5/28 is not a number.

You may want to remove the slash and everything following it before splitting by the period:

line = line.Split('/')[0];
string[] ip1 = line.Split('.');
....
BambooleanLogic
  • 7,530
  • 3
  • 30
  • 56
0

This Code will give you all the integers in a string ;

List<int> integer = new List<int>();
string number="";
foreach(char o in yourString)
{
    try
    {
        Convert.ToInt32(Convert.ToString(o));//try if o == an integer
        number+=o;
    }
    catch
    {
        if(number!="")
        {
            integer.Add(Convert.ToInt32(number));
            number="";
        }
    }
}
TC Alper Tokcan
  • 369
  • 1
  • 13
0

That's the shortest I could think of:

int[] ipArray = "92.44.12.5/28".Split('.', '/').Select(int.Parse).ToArray();
Dimitar Dimitrov
  • 14,868
  • 8
  • 51
  • 79
0

I can't add any improvement on the other answers, but as an alternative, there is also:

System.Net.IPAddress.Parse("92.44.12.5/28".Split('/').First()).GetAddressBytes().Last()
mungflesh
  • 776
  • 11
  • 22
0

Please try out below code, it gives output per your expectation

string line = "92.44.12.5/28";
string[] ip1 = line.Split('.');
int[] ipArray = Array.ConvertAll(ip1, new Converter<string, int>(StringToInt));

 public static int StringToInt(string value)
        {
            value = value.Contains('/') ? value.Split('/')[0] : value;  
            int result = 0;
                int.TryParse(value, out result);
            return result;
        }
Keshavdas M
  • 674
  • 2
  • 7
  • 25