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.
Related
I have an input stream which has fields separated by tab(\t)
which looks like this
String str = " acc123\tdpId123\t2011-01-01\t2022-01-01\thello#xyz.com\tIN\t1233\tSOMETHING ";
which works fine when I do str = str.trim(); and
strArray = str.split("\t", -1);
strArray=["acc123","dpId123","2011-01-01","2022-01-01","hello#xyz.com","IN","1233","SOMETHING"] will give size as 8
But last field in the input record is not mandatory and can be skipped.
So the input can look like this too.
String str1 = "acc123\tdpId123\t2011-01-01\t2022-01-01\thello#xyz.com\tIN\t1233\t";
but in this case last field should be empty but when I use this string after trim and split my size is 7
str1 = str1.trim();
strArray = str1.split("\t", -1);
strArray=["acc123","dpId123","2011-01-01","2022-01-01","hello#xyz.com","IN","1233"]will give size as 7
But I want
strArray=["acc123","dpId123","2011-01-01","2022-01-01","hello#xyz.com","IN","1233",""]
How can I avoid this situation?
There you go:
String str1 = " acc123\tdpId 123\t201 1-01-01\t2022-01-01\thello#xyz.com\tIN\t1233\t";
str1 = str1.replaceAll("^[ ]+", ""); // removing leading spaces
str1 = str1.replaceAll("[ ]+$", ""); // removing trailing spaces
String[] split = str1.split("\t", -1);
System.out.println(Arrays.toString(split));
System.out.println(split.length);
String#trim method also removes \t. To handle that I have removed only the leading and trailing spaces using regex.
Output:
[acc123, dpId 123, 201 1-01-01, 2022-01-01, hello#xyz.com, IN, 1233, ]
8
You can use split like so :
String[] split = str.split("\t", -1); // note the -1
To avoid spaces you can use
Arrays.stream(split).map(String::trim).toArray(String[]:new);
you can use limit parameter to solve this str.split("\t",-1) .
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.
read more about split limit in the docs.
Example:
public class GFG {
public static void main(String args[])
{
String str = "a\tb\tc\t";
String[] arrOfStr = str.split("\t",-1);
for (String a : arrOfStr)
System.out.println(a);
System.out.println(arrOfStr.length);
}
}
The conceptually correct way to do this in your case is to split first, only then trim first and last elements:
String[] array = str.split("\t");
array[0] = array[0].trim();
int last = array.length -1;
if (last > 0) {
array[last] = array[last].trim();
}
Also, if you know upfront how many fields there is supposed to be, then you should also use that knowledge, otherwise you can get an invalid number of fields still:
int fieldsCount = getExpectedFieldsCount();
String[] array = str.split("\t", fieldsCount);
Lastly, I advise you to not use whitespace as the data separator. Use something else. For example, see CSV format, it's a lot better for these things.
Try this (the result array is in the variable resultArray):
String str1 = "acc123\tdpId123\t2011-01-01\t2022-01-01\thello#xyz.com\tIN\t1233\t";
String[] strArray = str1.split("\t");
String regex = ".*\\t$";
String[] resultArray;
if (str1.matches(regex)) {
resultArray = new String[strArray.length + 1];
resultArray[strArray.length] = "";
} else {
resultArray = new String[strArray.length];
}
for (int i= 0; i < strArray.length; i++) {
resultArray[i] = strArray[i];
}
System.out.println(resultArray.length);
System.out.println(Arrays.toString(resultArray));
I have a String like this : String attributes = " foo boo, faa baa, fii bii," I want to get a result like this :
String[] result = {"foo boo", "faa baa", "fii bii"};
So my issue is how should to make split and trim in one shot i already split:
String[] result = attributes.split(",");
But the spaces still in the result :
String[] result = {" foo boo", " faa baa", " fii bii"};
^ ^ ^
I know that we can make a loop and make trim for every one but I want to makes it in shot.
Use regular expression \s*,\s* for splitting.
String result[] = attributes.split("\\s*,\\s*");
For Initial and Trailing Whitespaces
The previous solution still leaves initial and trailing white-spaces. So if we're expecting any of them, then we can use the following solution to remove the same:
String result[] = attributes.trim().split("\\s*,\\s*");
Using java 8 you can do it like this in one line
String[] result = Arrays.stream(attributes.split(",")).map(String::trim).toArray(String[]::new);
If there is no text between the commas, the following expression will not create empty elements:
String result[] = attributes.trim().split("\\s*,+\\s*,*\\s*");
You can do it with Google Guava library this way :
List<String> results = Splitter.on(",").trimResults().splitToList(attributes);
which I find quite elegant as the code is very explicit in what it does when you read it.
ApaceCommons StringUtils.stripAll function can be used to trim individual elements of an array. It leaves the null as null if some of your array elements are null.
Here,
String[] array = StringUtils.stripAll(attributes.split(","));
create your own custom function
private static String[] split_and_trim_in_one_shot(String string){
String[] result = string.split(",");
int array_length = result.length;
for(int i =0; i < array_length ; i++){
result[i]=result[i].trim();
}
return result;
Overload with a consideration for custom delimiter
private static String[] split_and_trim_in_one_shot(String string, String delimiter){
String[] result = string.split(delimiter);
int array_length = result.length;
for(int i =0; i < array_length ; i++){
result[i]=result[i].trim();
}
return result;
with streams
public static List<String> split(String str){
return Stream.of(str.split(","))
.map(String::trim)
.map (elem -> new String(elem))//optional
.collect(Collectors.toList());
What about spliting with comma and space:
String result[] = attributes.split(",\\s");
// given input
String attributes = " foo boo, faa baa, fii bii,";
// desired output
String[] result = {"foo boo", "faa baa", "fii bii"};
This should work:
String[] s = attributes.trim().split("[,]");
As answered by #Raman Sahasi:
before you split your string, you can trim the trailing and leading spaces. I've used the delimiter , as it was your only delimiter in your string
String result[] = attributes.trim().split("\\s*,[,\\s]*");
previously posted here: https://blog.oio.de/2012/08/23/split-comma-separated-strings-in-java/
Best way is:
value.split(",").map(function(x) {return x.trim()});
I have a Character array (not char array) and I want to convert it into a string by combining all the Characters in the array.
I have tried the following for a given Character[] a:
String s = new String(a) //given that a is a Character array
But this does not work since a is not a char array. I would appreciate any help.
Character[] a = ...
new String(ArrayUtils.toPrimitive(a));
ArrayUtils is part of Apache Commons Lang.
The most efficient way to do it is most likely this:
Character[] chars = ...
StringBuilder sb = new StringBuilder(chars.length);
for (Character c : chars)
sb.append(c.charValue());
String str = sb.toString();
Notes:
Using a StringBuilder avoids creating multiple intermediate strings.
Providing the initial size avoids reallocations.
Using charValue() avoids calling Character.toString() ...
However, I'd probably go with #Torious's elegant answer unless performance was a significant issue.
Incidentally, the JLS says that the compiler is permitted to optimize String concatenation expressions using equivalent StringBuilder code ... but it does not sanction that optimization across multiple statements. Therefore something like this:
String s = ""
for (Character c : chars) {
s += c;
}
is likely to do lots of separate concatenations, creating (and discarding) lots of intermediate strings.
Iterate and concatenate approach:
Character[] chars = {new Character('a'),new Character('b'),new Character('c')};
StringBuilder builder = new StringBuilder();
for (Character c : chars)
builder.append(c);
System.out.println(builder.toString());
Output:
abc
First convert the Character[] to char[], and use String.valueOf(char[]) to get the String as below:
char[] a1 = new char[a.length];
for(int i=0; i<a.length; i++) {
a1[i] = a[i].charValue();
}
String text = String.valueOf(a1);
System.out.println(text);
It's probably slow, but for kicks here is an ugly one-liner that is different than the other approaches -
Arrays.toString(characterArray).replaceAll(", ", "").substring(1, characterArray.length + 1);
Probably an overkill, but on Java 8 you could do this:
Character[] chars = {new Character('a'),new Character('b'),new Character('c')};
String value = Arrays.stream(chars)
.map(Object::toString)
.collect( Collectors.joining() );
At each index, call the toString method, and concatenate the result to your String s.
how about creating your own method that iterates through the list of Character array then appending each value to your new string.
Something like this.
public String convertToString(Character[] s) {
String value;
if (s == null) {
return null;
}
Int length = s.length();
for (int i = 0; i < length; i++) {
value += s[i];
}
return value;
}
Actually, if you have Guava, you can use Chars.toArray() to produce char[] then simply send that result to String.valueOf().
int length = cArray.length;
String val="";
for (int i = 0; i < length; i++)
val += cArray[i];
System.out.println("String:\t"+val);
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));
I know of no easy way to do this. Suppose I have the following string-
"abcdefgh"
I want to get a string by replacing the third character 'c' with 'x'.
The long way out is this -
s1 = substring before third character = "ab" in this case
s2 = new character = "x" in this case
s3 = substring after third character = "defgh" in this case
finalString = s1 + s2 + s3
Is there a simpler way? There should be some function like
public String replace(int pos, char replacement)
Use StringBuilder#replace().
StringBuilder sb = new StringBuilder("abcdefgh");
sb.replace(2, 3, "x");
String output = sb.toString();
http://ideone.com/Tg5ut
You can convert the String to a char[] and then replace the character. Then convert the char[] back to a String.
String s = "asdf";
char[] arr = s.toCharArray();
arr[0] = 'b';
s = new String(arr);
No. There is no simpler way than to concatenate the pieces.
Try using a StringBuilder instead StringBuilder Java Page
Since every String is basically just a char[] anyway, you could just grab it and manipulate the individual chars that way.
Try the String.replace(Char oldChar, Char newChar) method or use a StringBuilder
How about:
String crap = "crap";
String replaced = crap.replace(crap.charAt(index), newchar);
but this will replace all instances of that character
String yourString = "abcdef"
String newString = yourString.replaceAll("c" , "x");
System.out.println("This is the replaced String: " + newString);
This is the replaced String: abxdef