I have a string sub1-sub2-sub3 which I want to split from right to left. Currently I am using split function like this which splits the string from left to right -
String str = "sub1-sub2-sub3";
System.out.println("Result :" + str.split("-", 2));
Elements in output :
sub1
sub2-sub3
Desired output :
sub1-sub2
sub3
Is there a way where I can split my string on - starting from right?
You could do a regex split on -(?!.*-):
String str = "sub1-sub2-sub3";
String[] parts = str.split("-(?!.*-)");
System.out.println(Arrays.toString(parts)); // [sub1-sub2, sub3]
The regex pattern used here will only match the final dash.
A generic solution as utility method that takes limit as input with java 8:
public List<String> splitReverse(String input, String regex, int limit) {
return Arrays.stream(reverse(input).split(regex, limit))
.map(this::reverse)
.collect(Collectors.toList());
}
private String reverse(String i){
return new StringBuilder(i).reverse().toString();
}
reverse() code taken from here
Input: sub1-sub2-sub3
Reverse input: 3bus-2bus-1bus
Split(rev,2): [3bus] , [2bus-1bus]
Reverse each: [sub3] , [sub1-sub2]
One way would be to reverse the string before the split and then reverse the resulting strings.
String str = "sub1-sub2-sub3";
Arrays.stream(StringUtils.reverse(str).split("-",2))
.map(StringUtils::reverse)
.forEach(System.out::println);
Output:
sub3
sub1-sub2
It won't yield the same result as requested but maybe it will help.
P.S. util class used is from apache: org.apache.commons.lang3.StringUtils
A quick and dirty solution i cam up with would be
String str = "sub1-sub2-sub3";
str = StringUtils.reverse(str);
String[] split = str.split("-", 2);
split[0] = StringUtils.reverse(split[0]);
split[1] = StringUtils.reverse(split[1]);
System.out.println("Result :" + split[0] + " #### " + split[1]);
another way would be java how to split string from end
The below solution worked for me fine :
str.substring(0, str.lastIndexOf("-"));
str.substring(str.lastIndexOf("-"));
Related
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
I have a string in the form "/A/B/C/D". Is there a regex or a simple way to capture this into a String array of the form [/A, B, C, D]? Essentially, split on "/" but retain the first instance of the delimiter? I can be guaranteed that the input string will have "/" as the first character and at least one "/" following the first. My attempt has been this so far:
private String[] customSplit(String input) {
if (!input.startsWith("/")) {
input = "/" + input;
}
String[] output = input.split("/");
output[1] = "/" + output[1];
return output;
}
The above is a bit clunky though (and has an empty "" spot at index 0) so any suggestions?
You can use a negative lookahead in split to avoid split on first delimiter:
String[] toks = "/A/B/C/D".split("(?!^)/");
//=> [/A, B, C, D]
Here (?!^) is a negative lookahead that will skip start position for delimiter /
RegEx Demo
A dirty solution..but at least should work.
It assumes that you have at least 2 elements in the string, otherwise you've to add some error handling code, but from what you've written it should always be like that.
private String[] customSplit(String input) {
String preparedInput=input;
if (input.startsWith("/")) {
preparedInput=input.substring(1);
}
String[] output = preparedInput.split("/");
output[0] = "/" + output[0];
return output;
}
Another way is:
private String[] customSplit(String input) {
String[] output = input.substring(1).split("/");
output[0] = "/" + output[0];
return output;
}
This is some code for reversing characters in a string using StringBuffer:
String sh = "ABCDE";
System.out.println(sh + " -> " + new StringBuffer(sh).reverse());
Is there any similar way to reverse words in a string using StringBuffer?
Input: "I Need It" and
Output should be: "It Need I"
You may use StringUtils reverseDelimited:
Reverses a String that is delimited by a specific character.
The Strings between the delimiters are not reversed. Thus java.lang.String becomes String.lang.java (if the delimiter is '.').
So in your case we will use space as a delimiter:
import org.apache.commons.lang.StringUtils;
String reversed = StringUtils.reverseDelimited(sh, ' ');
You may also find a more lengthy solution without it here.
Using only JDK methods
String input = "I Need It";
String[] array = input.split(" ");
List<String> list = Arrays.asList(array);
Collections.reverse(list);
String output = String.join(" ", list);
System.out.println(output);
And result is It Need I
I am having a hard time figuring with out. Say I have String like this
String s could equal
s = "{1,4,204,3}"
at another time it could equal
s = "&5,3,5,20&"
or it could equal at another time
s = "/4,2,41,23/"
Is there any way I could just extract the numbers out of this string and make a char array for example?
You can use regex for this sample:
String s = "&5,3,5,20&";
System.out.println(s.replaceAll("[^0-9,]", ""));
result:
5,3,5,20
It will replace all the non word except numbers and commas. If you want to extract all the number you can just call split method -> String [] sArray = s.split(","); and iterate to all the array to extract all the number between commas.
You can use RegEx and extract all the digits from the string.
stringWithOnlyNumbers = str.replaceAll("[^\\d,]+","");
After this you can use split() using deliminator ',' to get the numbers in an array.
I think split() with replace() must help you with that
Use regular expressions
String a = "asdf4sdf5323ki";
String regex = "([0-9]*)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(a);
while (matcher.find())
{
String group = matcher.group(1);
if (group.length() > 0)
{
System.out.println(group);
}
}
from your cases, if the pattern of string is same in all cases, then something like below would work, check for any exceptions, not mentioned here :
String[] sArr= s.split(",");
sArr[0] = sArr[0].substring(1);
sArr[sArr.length()-1] =sArr[sArr.length()-1].substring(0,sArr[sArr.length()-1].length()-1);
then convert the String[] to char[] , here is an example converter method
You can use Scanner class with , delimiter
String s = "{1,4,204,3}";
Scanner in = new Scanner(s.substring(1, s.length() - 1)); // Will scan the 1,4,204,3 part
in.useDelimiter(",");
while(in.hasNextInt()){
int x = in.nextInt();
System.out.print(x + " ");
// do something with x
}
The above will print:
1 4 204 3
I have a String and I want to get the words before and after the " - " (dash). How can I do that?
example:
String:
"First part - Second part"
output:
first: First part
second: Second part
With no error-checking or safety, this could work:
String[] parts = theString.split("-");
String first = parts[0];
String second = parts[1];
Easy: use the String.split method.
Example :
final String s = "Before-After";
final String before = s.split("-")[0]; // "Before"
final String after = s.split("-")[1]; // "After"
Note that I'm leaving error-checking and white-space trimming up to you!
int indexOfDash = s.indexOf('-');
String before = s.substring(0, indexOfDash);
String after = s.substring(indexOfDash + 1);
Reading the javadoc helps finding answers to such questions.
#Test
public void testSplit() {
String str = "First part - Second part";
String strs[] = str.split("-");
for (String s : strs) {
System.out.println(s);
}
}
Output:
First part
Second part
use indexOf() and substring() method of String class, for the example given you can also use split() method