Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: remove all characters after point

Tags:

java

I got a quick question, I got the following code

String chapterNumber = "14.2.1";

how can I achieve to get a String like the following out of my "chapterNumber"

String mainChapterNumber = "14";

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

like image 946
James Carter Avatar asked Feb 19 '13 14:02

James Carter


People also ask

How do you delete everything after a character in Java?

Use the String. slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str. indexOf('[')); .

How do you remove text after space in Java?

trim() so it can remove the spaces in start and in end. Don't forget to trim the string.

How do I remove all characters before a character in Java?

s1. trim() . trim() removes spaces before the first character (which isn't a whitespace, such as letters, numbers etc.)


2 Answers

If it's only the first portion of the input string you want, you should do

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

The second argument of split (2) indicates that we should only split on the first occurrence of .; it's faster than splitting on all instances of . which is what would happen if we didn't supply this second argument.


Relevant Documentation

  • split
like image 159
arshajii Avatar answered Oct 01 '22 07:10

arshajii


Just use the following:

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

This will return a substring of your current chapter number starting from the first character which is placed in index number 0 and ending before the first appearance of "."

like image 35
Michael Avatar answered Oct 01 '22 06:10

Michael