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...
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?
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)
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("_"));
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];
Guava has Splitter
List<String> pieces = Splitter.on("_").splitToList("14.015_AUDI");
String numberPart = parts.get(0);
String audi = parts.get(1);