Slice string in java - 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));

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.

how to extract the last element in a String

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

Split the string with delimiter

I have a String as param1=HUvguys83789r8==== i have to split this with = delimiter. I have tried with String.split("=") as well as i have used StringUtils too but i cannot split it correctly. Can some one help me out for this.
String parameters = "param1=HUvguys83789r8===="
String[] string = StringUtils.split(parameters, "=");
parameters.split("=");
And i got my output as [param1, HUvguys83789r8]
I need the output as [param1, HUvguys83789r8====]
You really only want to split on the first occurrence of =, so do that
parameters.split("=", 2)
The overloaded split(String, int) javadoc states
If the limit n is greater than zero then the pattern will be applied
at most n - 1 times, the array's length will be no greater than n, and
the array's last entry will contain all input beyond the last matched
delimiter.
I would use String#indexOf(char ch) like so,
private static String[] splitParam(String in) {
int p = in.indexOf('=');
if (p > -1) {
String key = in.substring(0, p);
String value = in.substring(p + 1);
return new String[] {key, value};
}
return null;
}
public static void main(String[] args) {
String parameters = "param1=HUvguys83789r8====";
System.out.println(Arrays.toString(splitParam(parameters)));
}
Output is
[param1, HUvguys83789r8====]
Just split once using the alternate version of split():
String[] strings = parameters.split("=", 2); // specify max 2 parts
Test code:
String parameters = "param1=HUvguys83789r8====";
String[] strings = parameters.split("=",2);
System.out.println(Arrays.toString(strings));
Output:
[param1, HUvguys83789r8====]
i think you need :
String parameters = "param1=HUvguys83789r8====";
String[] string = parameters.split("\\w=\\w");
String part1 = string[0]; // param
String part2 = string[1]; // Uvguys83789r8====
System.out.println(part1);
System.out.println(part2);
make sure to escape the slashes to make it java compliant

replace string in java using string builder

I have a String in java :
String str = "150,def,ghi,jkl";
I want to get sub string till first comma, do some manipulations on it and then replace it by modified string.
My code :
StringBuilder sBuilder = new StringBuilder(str);
String[] temp = str.split(",");
String newVal = Integer.parseInt(temp[0])*10+"";
int i=0;
for(i=0; i<str.length(); i++){
if(str.charAt(i)==',') break;
}
sBuilder.replace(0, i, newVal);
What is the best way to do this because I am working on big data this code will be called millions of times, I am wondering if there is possibility of avoiding for loop.
You also can use the method replace() of String Object itself.
String str = "150,def,ghi,jkl";
String[] temp = str.split(",");
String newVal = Integer.parseInt(temp[0])*10+"";
String newstr = newVal + str.substring(str.indexOf(","),str.length());
String str = "150,def,ghi,jkl";
String newVal = Integer.parseInt(str.substring(0,str.indexOf(",")))*10+"";
This should at least avoid excessive String concatenation and regular expressions.
String prefix = sBuilder.substring(0, sBuilder.indexOf(","));
String newVal = ...;
sBuilder.replace(0, newVal.length(), newVal);
Don't now if this is useful to you but we often use :
org.springframework.util.StringUtils
In the StringUtils class you have alot of useful methods for comma seperated files.

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());
}

Categories

Resources