how to extract the last element in a String - java

I need to extract the amount in a string below, I need the string of "1.50",
eg. CARD,S1234,1.50
I try to use indexOf, but then there might be few commas. If I use . for reference, the amount might be 100.50. Either way is not working.
Any idea?

String.split (",") - get last element of the returned array:
String str = "CARD,S1234,1.50";
String arr[] = str.split (",");
System.out.println(arr[arr.length -1]);

Use the .split() method:
String[] arrayString = "CARD,S1234,1.50".split(",");
String lastString = arrayString[arrayString.length - 1];

String s = "CARD,S1234,1.50";
String last = s.substring(s.lastIndexOf(",")+1, s.length);

Related

What is the efficient way to get a specific substring from a string in Java?

I have a string as follows:
"[error=<null>,EntityID=105378032, Context=<null>]"
and i want to extract the EntityID( in this case 105378032), but i want a generalize solution of doing it.
What is the most efficient way of doing it.
I don't want to traverse the string and get that part.
Did you try regex like .*EntityID=(.*?),.* which mean get the group of characters between EntityID= and the next comma , using replaceAll :
String str = "[error=,EntityID=105378032, Context=]";
System.out.println(str.replaceAll(".*EntityID=(.*?),.*", "$1"));// output 105378032
regex demo
Using Regular expressions seems to be the best way out.
This code works:
String str = "[error=,EntityID=105378032, Context=]";
String[] arr = str.split("EntityID="); //splits it on the part "EntityID="
String[] arr1 = arr[1].split(","); // splits it on the next comma in the 'right' half of your string.
System.out.println(arr1[0]); //prints the 'left' half before the comma.
Ideone link here.
Hope this helps!
You can use this method it's work like a charm
public static String getSubString(String mainString, String lastString, String startString) {
String endString = "";
int endIndex = mainString.indexOf(lastString);
int startIndex = mainString.indexOf(startString);
endString = mainString.substring(startIndex, endIndex);
return endString;
}
Result:
String resultStr = getSubString(yourFullString,",Context","EntityID=");
Happy codding.

Parsing string from the name

I am trying to parse the certain name from the filename.
The examples of File names are
xs_1234323_00_32
sf_12345233_99_12
fs_01923122_12_12
I used String parsedname= child.getName().substring(4.9) to get the 1234323 out of the first line. Instead, how do I format it for the above 3 to output only the middle numbers(between the two _)? Something using split?
one line solution
String n = str.replaceAll("\\D+(\\d+).+", "$1");
most efficent solution
int i = str.indexOf('_');
int j = str.indexOf('_', i + 1);
String n = str.substring(i + 1, j);
String [] tokens = filename.split("_");
/* xs_1234323_00_32 would be
[0]=>xs [1]=> 1234323 [2]=> 00 [3] => 32
*/
String middleNumber = tokens[2];
You can try using split using the '_' delimiter.
The String.split methods splits this string around matches of the given ;parameter. So use like this
String[] output = input.split("_");
here output[1] will be your desired result
ANd input will be like
String input = "xs_1234323_00_32"
I would do this:
filename.split("_", 3)[1]
The second argument of split indicates the maximum number of pieces the string should be split into, in your case you only need 3. This will be faster than using the single-argument version of split, which will continue splitting on the delimiter unnecessarily.

String Java find spaces

I have a phrase on a string and I want to split it on other 5 or more string without spaces.
For example:
String test = "hi/ please hepl meok?";
and I want :
String temp1 = "hi/";
String temp2 = "please";
String temp3 = "help";
String temp4 = "meok?";
I dont want to add that in an array, because I want to split the temp4 to 3 more strings.
eg
->> temp4 after splitting:
temp4 = "me"
temp5 = "ok"
temp6 = "?"
This Question is asked because I want to write a method to decode a String phrase from a LinkedHashMap set with some decodes. Thanks. If my way is wrong please guide me! :)
I dont want to add that in an array, because I want to split the temp4 to 3 more strings. eg
Split the string with String#split, then assign the parts of the resulting array to your individual variables:
String[] parts = theOriginalString.split(" ");
String temp1 = parts[0];
String temp2 = parts[1];
String temp3 = parts[2];
String temp4 = parts[3];
String temp5 = parts[4];
I find the idea of making these separate named variables a bit suspect, but I can see use cases — for instance, if you're about to embark on a bunch of logic where useful names make the code clearer.
Given your string, split() will do the trick
String tokens[] = test.split(" ");
tokens[0] will then be "hi/", tokens[1] will be "please" and so on.
EDIT you're going to be storing your strings in an array first in any case when split is used, use StringTokenizer if you want to loop through them individually.
StringTokenizer st = new StringTokenizer(test);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}

Java Strings with Delimiters

I have a string "content/users/user/missions/mission" .I need to get "content/users/user/missions" from it [i.e. string upto the last delimiter] .How to proceed ?
If your requirement is that simple then you could do the following:
String string = "content/users/user/missions/mission";
String newString = string.substring(0, string.lastIndexOf('/'));
There are more fancy ways of doing this, regex could be one.
Use lastIndexOf and substring methods from String class.
String str = "content/users/user/missions/mission";
String result = str.substring(0,str.lastIndexOf('/'));

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?
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);
you can use substring!
"substring(int begIndex, int endIndex)"
eg:
String name = "14.015_AUDI";
System.out.println(name.substring(0,6));

Categories

Resources