java split () method - java

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

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

Java - replace comma alternatively

I have a String which contains data separated by comma (,) for each value. I wanna replace comma by some other delimiter. But need to replace comma alternatively.
That means second, forth, sixth occurrence of comma need to be replaced. Is there any possible way to do?
Eg: "a,b,c,d,e,f" is the string available and want the output as "a,b c,d e,f".
You can use some regex with replaceAll like this :
String str = "a,b,c,d,e,f";
String delimiter = " ";//You can use any delimiter i use space in your case
str = str.replaceAll("([a-zA-Z]+,[a-zA-Z]+)(,)", "$1" + delimiter);
System.out.println(str);
result
a,b c,d e,f
regex demo
Here is a simple code that uses array of characters to do the task.
public class ReplaceAlternateCommas {
public static void main(String[] args) {
String str = "a,bg,dfg,d,v";
System.out.println(str);
char[] charArray = str.toCharArray();
int commaCount=0;
char replacementChar = ' ';//replace comma with this character
for(int i=0;i<charArray.length;i++){
char ch = charArray[i];
if(ch==','){
commaCount++;
if(commaCount%2==0){
charArray[i]=replacementChar;
}
}
}
str = new String(charArray);
System.out.println(str);
}
}
If you dont want to use character array you can use regex or StringBuilder .

Splitting string with letters and letter combinations divided by space into array in Java

I am making an app for Android, and it turned out that I do really need to "split" the string (which is actually entered by the user) to the parts and then put them into array. The string itself is supposed to contain letter or letter combination (2 letters) and then space, letter or combination and space... for example "ab c de f g hi j". So for this particular example array would be like array[1]= "ab", array[2]= "c", array[3]= "de" and so on... And each letter or letter combination is supposed to get to array. I've tried to use charAt with IF, but it doesn't seem to work. I'm novice to java so the only possible solution I see is to "cut" the string from the beginning and put it to array, but aren't there any other ways?
Thanks.
Using split method from String
String[] myString = userString.split(" ");
Example:
Input:
String userString = "Hello world";
String[] myString = userString.split(" ");
Output:
myString[0] = "Hello"
myString[1] = "world"
You can use the split method of String class.
String inputString = "ab c d efg h";
String[] arrayOfWords = inputString.split(" ");
for(String word:arrayOfWords) {
System.out.println(word);
}
if your inputString have any other delimeter instead of space between the words, you can use that inside the split method.
Example
String inputString = "ab,c,d,efg,h";
String[] arrayOfWords = inputString.split(",");
for(String word:arrayOfWords) {
System.out.println(word);
}

String split function in 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

How to put Java String to array

I have a java String of a list of numbers with comma separated and i want to put this into an array only the numbers. How can i achieve this?
String result=",17,18,19,";
First remove leading commas:
result = result.replaceFirst("^,", "");
If you don't do the above step, then you will end up with leading empty elements of your array. Lastly split the String by commas (note, this will not result in any trailing empty elements):
String[] arr = result.split(",");
One liner:
String[] arr = result.replaceFirst("^,", "").split(",");
String[] myArray = result.split(",");
This returns an array separated by your argument value, which can be a regular expression.
Try split()
Assuming this as a fixed format,
String result=",17,18,19,";
String[] resultarray= result.substring(1,result.length()).split(",");
for (String string : resultarray) {
System.out.println(string);
}
//output : 17 18 19
That split() method returns
the array of strings computed by splitting this string around matches of the given regular expression
You can do like this :
String result ="1,2,3,4";
String[] nums = result.spilt(","); // num[0]=1 , num[1] = 2 and so on..
String result=",17,18,19,";
String[] resultArray = result.split(",");
System.out.printf("Elements in the array are: ");
for(String resultArr:resultArray)
{
System.out.println(resultArr);
}

Categories

Resources