Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using string.split() with a decimal - not working

Tags:

java

string

regex

I'm trying to split a line of text into multiple parts. Each element of the text is separated by a period. I'm using string.split("."); to split the text into an array of Strings, but not getting anywhere.

Here is a sample of the code:

String fileName = "testing.one.two";

String[] fileNameSplit = fileName.split(".");

System.out.println(fileNameSplit[0]);

The funny thing is, when I try ":" instead of ".", it works? How can I get it to work for a period?

like image 404
CodyBugstein Avatar asked Nov 19 '12 19:11

CodyBugstein


People also ask

How do you split a string into values?

Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.

How do you divide decimals in Java?

If you need to divide two integers and get a decimal result, you can cast either the numerator or denominator to double before the operation. XResearchsource is performed. In this example, we'll cast a to double so we get a decimal result: int a = 55; int b = 25; double r = (double) a / b // The answer is 2.2.


3 Answers

String.split() accepts a regular expression (regex for short) and dot is a special char in regexes. It means "match all chars except newlines". So you must escape it with a leading backslash. But the leading backslash is a special character in java string literals. It denotes an escape sequence. So it must be escaped too, with another leading backslash. Like this:

fileName.split("\\.");
like image 115
Asaph Avatar answered Oct 09 '22 17:10

Asaph


Try this one: fileName.split("\\.");

like image 27
Juvanis Avatar answered Oct 09 '22 16:10

Juvanis


fileName.split(".");

should be

fileName.split("\\.");

. is special character and split() accepts regex. So, you need to escape the special characters.

A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler. Please read this documentation.

like image 4
kosa Avatar answered Oct 09 '22 16:10

kosa