Java: delete all characters after dot

I had a quick question, I got the following code

String chapterNumber = "14.2.1"; 

how can I get to get a line from the next "my" section "<section number"

 String mainChapterNumber = "14"; 

Edit: I want all numbers in int / String (doesn't matter to me) to the first point

+7
source share
8 answers

If this is only the first part of the input string you want, you should do

 String mainChapterNumber = chapterNumber.split("\\.", 2)[0]; 

The second argument to split ( 2 ) indicates that we should only split into the first occurrence . ; it is faster than splitting into all instances . , which will happen if we do not present this second argument.


Related Documentation

+25
source

Just use the following:

 String mainChapterNum = chapterNumber.substring(0, chapterNumber.indexOf(".")); 

This will return a substring of your current chapter number, starting with the first character, which is placed at index number 0 and ends before the first "."

+8
source
 String chapterNumber = "1.2.1"; int index = chapterNumber.indexOf("."); String mainChapterNumber = chapterNumber.substring(0,index); 
+4
source

Since we do not have any evidence that you are actually trying to do something, I will make an offer instead of giving you the code.

Try playing with the indices of your row. Find the index of the first point, and then use the substring method to save the substring between the beginning and what happened.

+1
source

There are several ways to do this. The simplest one I would recommend is to use a substring, and indexOf: Like this:

 String result = chapterNumber.substring(0, chapterNumber.indexOf(".")); 

Another way to do this would be as follows:

 String result = chapterNumber.split("\\.")[0]; 
+1
source

Try as below ...

 String chapterNumber = "1.2.1"; String[] getdt = chapterNumber.split("\\."); String mainChapterNumber = getdt[0]; 
0
source
 String mainChapterNumber = chapterNumber.substring(0,chapterNumber.indexOf(".")); 
0
source

For write-only, another solution using the Guava delimiter :

 String mainChapterNumber = Iterables.get(Splitter.on('.').split(chapterNumber), 0); 

This has the advantage that do not use regex machines (which are not lightweight, do not use the decision made in a loop).

0
source

All Articles