String split function in Java - java

I have a String and I want to split it by ","
If suppose I have a String like,
String test = "aa,bb,cc";
now I can split it by,
String[] spl = test.split(",");
And the spl.length is 3
If suppose my String is
String test = ",,,";
Here the splitted String length is 0. But my expected answer is 3.
My test String is dynamaic value and it may varies like, Now think I have a String like
String test = ",aa,dd,,,,,ff,gg"
Now the splited array length is 4. But I expected answer is 9
And I need to split by "," and I need the aa position at spl[1] and dd position as spl[2] and ff position as spl[7]
Can someone give the suggestion about to solve this issue..

Use split() with -1 as limit
public static void main(String[] args) {
String test = ",,,";
System.out.println(Arrays.toString(test.split(",", -1))); // adds leading and trailing empty Strings .
// so effectively its like adding "" before , after and between each ","
String test1 = "aa,bb,cc";
System.out.println(Arrays.toString(test1.split(",",-1)));
}
O/P :
[, , , ] -- > Length =4
[aa, bb, cc]

To get the behavior you want you can just replace "," by " ,":
String test = ",,";
test = test.replace(",", " ,");
System.out.println((test.split(",").length));

With the split() function, java separates a String by the Substring of your choice. If there is nothing between them, the field will not be null, it will just be skipped.
In other programming languages, you could come across something like this:
String example = ',,,'
String[] example2 = example.split(',')
print(example2.length())
This could also deliver 4. Because there are 4 spaces around the ',' chars:
1,2,3,4

Related

Remove/Replace the part of string value

I have to remove the words from the given string.
Example :
Input:
"H|013450107776|10/15/2019
D|0000TXN001|10/15/2019|013450107806|LCUATADA05|1000.00|PAYMENT FOR SERVICE|Successful"
Output:
"H|013450107776|10/15/2019
D|0000TXN001|10/15/2019|013450107806|LCUATADA05|1000.00|Successful"
Note:"PAYMENT FOR SERVICE" is a dynamic string value it can be any thing.
I have tried using replace() and regex function but i am not able to get the exact output.
The following code will work.
public static String replace(String original, String toRemove) {
Arrays.stream(original.split("\\|"))
.filter(s -> !(s.equals(toRemove)))
.collect(Collectors.joining("|"));
}
First, create a Stream of Strings (Stream<String>) that are originally separated by |.
Second, filter them, so only Strings that are not equal to toRemove remain in the Stream.
Thrid, collect using joining with a joining character |.
Splitting your string on "|" and assuming the word you want to replace is always at the same position, the below does what you need :
String s = "H|013450107776|10/15/2019D|0000TXN001|10/15/2019|013450107806|LCUATADA05|1000.00|PAYMENT FOR SERVICE|Successful";
String result = s.replace(s.split("\\|")[8], "");
System.out.println(result);
It prints out :
H|013450107776|10/15/2019D|0000TXN001|10/15/2019|013450107806|LCUATADA05|1000.00||Successful
Here is a trick I like to use:
String input = "H|013450107776|10/15/2019D|0000TXN001|10/15/2019|013450107806|LCUATADA05|1000.00|PAYMENT FOR SERVICE|Successful";
System.out.println(input);
input = "|" + input + "|";
String output = input.replaceFirst("\\|PAYMENT FOR SERVICE\\|", "|");
output = output.substring(1, output.length()-1);
System.out.println(output);
To see how this works, consider the following input:
A|B|C
Let's say that we want to remove A. We first form the string:
|A|B|C|
Then, we replace |A| with just |, to give:
|B|C|
Finally, we strip those initial added pipe separators to give:
B|C
String str = "H|013450107776|10/15/2019D|0000TXN001|10/15/2019|013450107806|LCUATADA05|1000.00|PAYMENT FOR SERVICE|Successful";
System.out.println(str.replaceAll("PAYMENT FOR SERVICE|", ""));`
public static void main(String[] args) {
String str = "H|013450107776|10/15/2019D|0000TXN001|10/15/2019|013450107806|LCUATADA05|1000.00|PAYMENT FOR SERVICE|Successful";
String scut = "PAYMENT FOR SERVICE";
System.out.println(str.substring(0,str.indexOf(scut)) + str.substring(str.indexOf(scut)+scut.length()+1,str.length()));
}
replace all uppercase words between || with "|"
for example: "|A G G SLG SD GSD G|" -> "|"
input.replaceAll("\\|[A-Z\\s]+\\|","|")
\\s - any whitespace symbol
A-Z - symbols between A and Z
more info : https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

Remove trailing substring from String in Java

I am looking to remove parts of a string if it ends in a certain string.
An example would be to take this string: "am.sunrise.ios#2x.png"
And remove the #2x.png so it looks like: "am.sunrise.ios"
How would I go about checking to see if the end of a string contains "#2x.png" and remove it?
You could check the lastIndexOf, and if it exists in the string, use substring to remove it:
String str = "am.sunrise.ios#2x.png";
String search = "#2x.png";
int index = str.lastIndexOf(search);
if (index > 0) {
str = str.substring(0, index);
}
Assuming you have a string initialized as String file = "am.sunrise.ios#2x.png";.
if(file.endsWith("#2x.png"))
file = file.substring(0, file.lastIndexOf("#2x.png"));
The endsWith(String) method returns a boolean determining if the string has a certain suffix. Depending on that you can replace the string with a substring of itself starting with the first character and ending before the index of the character that you are trying to remove.
private static String removeSuffixIfExists(String key, String suffix) {
return key.endswith(suffix)
? key.substring(0, key.length() - suffix.length())
: key;
}
}
String suffix = "#2x.png";
String key = "am.sunrise.ios#2x.png";
String output = removeSuffixIfExists(key, suffix);
public static void main(String [] args){
String word = "am.sunrise.ios#2x.png";
word = word.replace("#2x.png", "");
System.out.println(word);
}
If you want to generally remove entire content of string from # till end you can use
yourString = yourString.replaceAll("#.*","");
where #.* is regex (regular expression) representing substring starting with # and having any character after it (represented by .) zero or more times (represented by *).
In case there will be no #xxx part your string will be unchanged.
If you want to change only this particular substring #2x.png (and not substirng like #3x.png) while making sure that it is placed at end of your string you can use
yourString = yourString.replaceAll("#2x\\.png$","");
where
$ represents end of string
\\. represents . literal (we need to escape it since like shown earlier . is metacharacter representing any character)
Since I was trying to do this on an ArrayList of items similarly styled I ended up using the following code:
for (int image = 0; image < IBImages.size(); image++) {
IBImages.set(image, IBImages.get(image).split("~")[0].split("#")[0].split(".png")[0]);
}
If I have a list of images with the names
[am.sunrise.ios.png, am.sunrise.ios#2x.png, am.sunrise.ios#3x.png, am.sunrise.ios~ipad.png, am.sunrise.ios~ipad#2x.png]
This allows me to split the string into 2 parts.
For example, "am.sunrise.ios~ipad.png" will be split into "am.sunrise.ios" and "~ipad.png" if I split on "~". I can just get the first part back by referencing [0]. Therefore I get what I'm looking for in one line of code.
Note that image is "am.sunrise.ios~ipad.png"
You could use String.split():
public static void main(String [] args){
String word = "am.sunrise.ios#2x.png";
String[] parts = word.split("#");
if (parts.length == 2) {
System.out.println("looks like user#host...");
System.out.println("User: " + parts[0]);
System.out.println("Host: " + parts[1]);
}
}
Then you haven an array of Strings, where the first element contains the part before "#" and the second element the part after the "#".
Combining the answers 1 and 2:
String str = "am.sunrise.ios#2x.png";
String search = "#2x.png";
if (str.endsWith(search)) {
str = str.substring(0, str.lastIndexOf(search));
}

Java Character change of a String

i have java String variables format with(include spaces) String id = "CA T 4443" i need to get my String value as id=CA4443 need to remove T and spaces. can any java expert help me to concatenate these characters.
my value array
CA T 4443
CB T 4562
CG T 6365
DA T 5552
CX T 9875
CS T 5454
RA T 2377
second challenge
CAF T 444352
CBAD T 4562
CG T 636535
DA T 555255
CX T 98755665
CS T 545455
RA T 237766
i need to get as (only 1st two latter and last 4 digits)
CA4352
CB4562
CG6535
DA5255
CX5665
CS5455
RA7766
If it is always two lettes, a space, a T, and a number then you could do :
String id = "CA T 4443"
String result = id.substring(0, 2) + id.substring(5, id.length);
Or you could just do :
String result = id.replace(" T ", "");
Just do this:
public static String getFormatedValue(String data) {
String[] split = data.split(" ", 3);
return split[0] + split[2];
}
This will take the first and last section, and skip the middle T section.
You have several things going on - it's hard to tell what's the best approach without seeing the raw data.
easiest / most fragile: if you know for a fact that every line is exactly the same length, "CA T 4443" you can just manually grab the characters at that position with substring or directly from the char array. This will break if one line is larger, probably safer to trim() the string before calling substring
or you can call split:
String id = "CA T 4443";
String[] split = id.split(" "); -> gives ["CA","T", "4443"]
A bit more flexible with lengths but depends on formatting. Splitting on a regex for whitespace if your data is possibly dirty
or just grab pieces through regex matching.
Depends on how normalized your data is.
EDIT: For the firtst challenge only
If it is always that the IDs have T between the two "segments" you are trying to concatenate, then following is my solution:
public static String makeID(String[] myValueArray){
String newID = "";
for (String s: myValueArray){
String[] previousID = s.split(" T ");
newID = newID + previousID[0] + previousID[1] + "\n";
}
return newID;
}

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.

java split () method

I've got a string '123' (yes, it's a string in my program). Could anyone explain, when I use this method:
String[] str1Array = str2.split(" ");
Why I got str1Array[0]='123' rather than str1Array[0]=1?
str2 does not contain any spaces, therefore split copies the entire contents of str2 to the first index of str1Array.
You would have to do:
String str2 = "1 2 3";
String[] str1Array = str2.split(" ");
Alternatively, to find every character in str2 you could do:
for (char ch : str2.toCharArray()){
System.out.println(ch);
}
You could also assign it to the array in the loop.
str2.split("") ;
Try this:to split each character in a string .
Output:
[, 1, 2, 3]
but it will return an empty first value.
str2.split("(?!^)");
Output :
[1, 2, 3]
the regular expression that you pass to the split() should have a match in the string so that it will split the string in places where there is a match found in the string. Here you are passing " " which is not found in '123' hence there is no split happening.
Because there's no space in your String.
If you want single chars, try char[] characters = str2.toCharArray()
Simple...You are trying to split string by space and in your string "123", there is no space
This is because the split() method literally splits the string based on the characters given as a parameter.
We remove the splitting characters and form a new String every time we find the splitting characters.
String[] strs = "123".split(" ");
The String "123" does not have the character " " (space) and therefore cannot be split apart. So returned is just a single item in the array - { "123" }.
To do the "Split" you must use a delimiter, in this case insert a "," between each number
public static void main(String[] args) {
String[] list = "123456".replaceAll("(\\d)", ",$1").substring(1)
.split(",");
for (String string : list) {
System.out.println(string);
}
}
Try this:
String str = "123";
String res = str.split("");
will return the following result:
1,2,3

Categories

Resources