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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 03:15:01

问题


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?


回答1:


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".




回答2:


Because "." is a special character, meaning "any character".

You need to escape it to be able to use it as the character ".":

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


来源:https://stackoverflow.com/questions/23818325/why-is-my-string-length-0-if-i-split-this-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!