Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice string in java

Tags:

java

string

excel

How slice string in java? I'm getting row's from csv, and xls, and there for example data in cell is like

14.015_AUDI

How can i say java that it must look only on part before _ ? So after manipulating i must have 14.015. In rails i'll do this with gsub, but how do this in java?

like image 327
byCoder Avatar asked Aug 26 '12 14:08

byCoder


2 Answers

You can use String#split:

String s = "14.015_AUDI";
String[] parts = s.split("_"); //returns an array with the 2 parts
String firstPart = parts[0]; //14.015

You should add error checking (that the size of the array is as expected for example)

like image 183
assylias Avatar answered Sep 28 '22 18:09

assylias


Instead of split that creates a new list and has two times copy, I would use substring which works on the original string and does not create new strings

String s = "14.015_AUDI";
String firstPart = s.substring(0, s.indexOf("_"));
like image 20
Masood_mj Avatar answered Sep 28 '22 18:09

Masood_mj