Say I have a string a such:
String str = "Kellogs Conflakes_$1.20";
How do I get the preceding values before the dollar ($) sign.
N.B: The prices could be varied say $1200.
Say I have a string a such:
String str = "Kellogs Conflakes_$1.20";
How do I get the preceding values before the dollar ($) sign.
N.B: The prices could be varied say $1200.
You can return the substring using substring and the index of the $ character.
str = str.substring(0, str.indexOf('$'));
You could use String.split(String s) which creates a String[].
String str = "Kellogs Conflakes_$1.20"; //Kellogs Conflakes_$1.20
String beforeDollarSign = String.split("$").get(0); //Kellogs Conflakes_
This will split the String str into a String[], and then gets the first element of that array.
Just do this for split str.split("$")
and store it on an array of String
.
String[] split = str.split("$");
And then get the first position of the array to get the values that you have before the $
System.out.println(split[0]); //Kellogs Conflakes_
At the position 1 you will have the rest of the line:
System.out.println(split[1]); //1.20
Try this:
public static void main(String[] args) {
String str = "Kellogs Conflakes_$1.20";
String[] abc=str.split("\ \$");
for(String i:abc)
{
System.out.println(i);
}
}
after this you can easily get abc[0]