Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to fetch numbers from string by java split() method

I have this code which takes an IP address(string) of the format 255.255.255.255 and needs to perform some post processing on those numbers (not posted here) but for which the string must be converted into an array of ints.

I have used here the split() method but it's not giving me the result. I saw other answers on sp doing it with regex but none of them worked for me.

import java.util.Scanner;
public class Main{
    public static void main(String args[]){
        String text;

        Scanner take=new Scanner(System.in);
        text=take.nextLine();
        String data[]=text.split(".",4);

        for(String w:data){
            System.out.println(w);
        }
        take.close();
    }
}

I have tried with the input 12.36.26.25

But it outputs 36.26.25 which was supposed to be like 12 36 26 25

like image 621
dutta.ari Avatar asked Jul 27 '26 16:07

dutta.ari


2 Answers

Use it like that:

        String example="12.36.26.25";
        String data[]=example.split("\\.");

        for(String w:data){
            System.out.println(w);
        }

And it will do what you want ;)

Using split(regex,limit) as you did will actually split on any character (since . is the regex for any character) and it will basically remove the first few characters

like image 95
Veselin Davidov Avatar answered Jul 29 '26 06:07

Veselin Davidov


Solution using java.util.regex package:

import java.util.regex.*;
public class Main{

     public static void main(String args[]){
        String text = "12.36.26.25";
        String separator = ".";
        String[] data = text.split(Pattern.quote(separator));
        System.out.println(data.length);
        for(String w: data){
            System.out.println(w);
        }
    }
}

The Pattern.quote will do the escaping.

like image 24
Sid Avatar answered Jul 29 '26 05:07

Sid