Slice string in java

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?

1

5 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)

3

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("_"));
4
String str = "14.015_AUDI";
String [] parts = str.split("_");
String numberPart = parts[0];
String audi = parts[1];

Should be shorter:

"14.015_AUDI".split("_")[0];
5

Guava has Splitter

List<String> pieces = Splitter.on("_").splitToList("14.015_AUDI");
String numberPart = parts.get(0);
String audi = parts.get(1);

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like