Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is my string.length 0 if I split this string? [duplicate]

This is probably a very easy question but I'm going to give you the code first.

import java.util.Scanner;

public class help {
public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);

    System.out.print("Give: ");
    String s = sc.next();

    String[] parts = s.split(".");

    System.out.println(parts.length);
}
}

Even if I give 192.168.1.1.1.1.1 or 1.2.3 or ... the parts.length will always be 0, can somebody please explain to me why and how I can let it be 4 if i enter 1.2.3.4?

like image 711
user3646130 Avatar asked Dec 15 '22 22:12

user3646130


1 Answers

You need s.split("\\.") because the argument to split is a regular expression. The . character in a regular expression means "any character", and you need to escape it with the backslash to have it mean "dot".

like image 191
Dawood ibn Kareem Avatar answered Feb 23 '23 00:02

Dawood ibn Kareem