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
Related
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("-"));
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'm trying to split some input from BufferedReader.readLine()
String delimiters = " ,()";
String[] s = in.readLine().split(delimiters);
This gives me a runtime error.
Things I have tried that don't work:
String delimiters = " ,\\(\\)";
String delimiters = " ,[()]";
String[] s = in.readLine().split(Pattern.quote("() ,"));
I tried replacing the () using .replaceAll, didn't work
I tried this:
input = input.replaceAll(Pattern.quote("("), " ");
input = input.replaceAll(Pattern.quote(")"), " ");
input = input.replaceAll(Pattern.quote(","), " ");
String[] s = input.split(" ");
but s[] ends up with blank slots that look like this -> "" no clue why its doing that
Mine works, for
String delimiters = "[ \\(\\)]"
Edit:
You forgot Square brakcets which represents, "Any of the characters in the box will be used as delimiters", its a regex.
Edit:
To remove the empty elements: Idea is to replace any anagram of set of delimiters to just 1 delimiter
Like.
// regex to match any anagram of a given set of delimiters in square brackets
String r = "(?!.*(.).*\1)[ \\(\\)]";
input = input.replaceAll(r, "(");
// this will result in having double or more combinations of a single delimiter, so replace them with just one
input = input.replaceAll("[(]+", "(");
Then you will have the input, with any single delimiter. Then use the split, it will not have any blank words.
From your comment:
but I am only input 1 line: (1,3), (6,5), (2,3), (9,1) and I need 13652391 so s[0] = 1, s[1]=3, ... but I get s[0] = "" s[1] = "" s[2] = 1
You get that because your delimiters are either " ", ",", "(" or ")" so it will split at every single delimiter, even if there is no other characters between them, in which case it will be split into an empty string.
There is an easy fix to this problem, just remove the empty elements!
List<String> list = Arrays.stream(
"(1,3), (6,5), (2,3), (9,1)".split("[(), ]")).filter(x -> !x.isEmpty())
.collect(Collectors.toList());
But then you get a List as the result instead of an array.
Another way to do this, is to replace "[(), ]" with "":
String result = "(1,3), (6,5), (2,3), (9,1)".replaceAll("[(), ]", "");
This will give you a string as a result. But from the comment I'm not sure whether you wanted a string or not. If you want an array, just call .split("") and it will be split into individual characters.
The question is we have to split the string and write how many words we have.
Scanner in = new Scanner(System.in);
String st = in.nextLine();
String[] tokens = st.split("[\\W]+");
When I gave the input as a new line and printed the no. of tokens .I have got the answer as one.But i want it as zero.What should i do? Here the delimiters are all the symbols.
Short answer: To get the tokens in str (determined by whitespace separators), you can do the following:
String str = ... //some string
str = str.trim() + " "; //modify the string for the reasons described below
String[] tokens = str.split("\\s+");
Longer answer:
First of all, the argument to split() is the delimiter - in this case one or more whitespace characters, which is "\\s+".
If you look carefully at the Javadoc of String#split(String, int) (which is what String#split(String) calls), you will see why it behaves like this.
If the expression does not match any part of the input then the resulting array has just one element, namely this string.
This is why "".split("\\s+") would return an array with one empty string [""], so you need to append the space to avoid this. " ".split("\\s+") returns an empty array with 0 elements, as you want.
When there is a positive-width match at the beginning of this string then an empty leading substring is included at the beginning of the resulting array.
This is why " a".split("\\s+") would return ["", "a"], so you need to trim() the string first to remove whitespace from the beginning.
If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
Since String#split(String) calls String#split(String, int) with the limit argument of zero, you can add whitespace to the end of the string without changing the number of words (because trailing empty strings will be discarded).
UPDATE:
If the delimiter is "\\W+", it's slightly different because you can't use trim() for that:
String str = ...
str = str.replaceAll("^\\W+", "") + " ";
String[] tokens = str.split("\\W+");
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String line = null;
while (!(line = in.nextLine()).isEmpty()) {
//logic
}
System.out.print("Empty Line");
}
output
Empty Line
I want to convert a infix operation to postfix operation. My code works when the input is given as already split expression through an array. But it doesn't when the input is given as the raw String expression.
String[] exp={"23","+","32"}//this works
String str="23 + 32";
String[]exp=str.split("//s+" );//this doesn't work
I think you have to use backslash instead of slash:
String[] exp = str.split("\\s+");
You had 2 issues I could see in your code. The first is that your second String[] has the same variable name as your first. The second is that you were using forward-slashes instead of back-slashes.
String[] exp = {"23","+","32"};
String str = "23 + 32";
String[] exp2 = str.split("\\s+"); // or " +"
System.out.println(Arrays.toString(exp));
System.out.println(Arrays.toString(exp2));
The above is working correctly for me.
I hope this helps.