Splitting expression with String#split() - java

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.

Related

How do I escape parentheses in java 7?

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.

Code to reverse words in a String using StringBuffer

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

Convert a string to an array of strings

If I have:
Scanner input = new Scanner(System.in);
System.out.println("Enter an infixed expression:");
String expression = input.nextLine();
String[] tokens;
How do I scan the infix expression around spaces one token at a time, from left to right and put in into an array of strings? Here a token is defined as an operand, operator, or parentheses symbol.
Example: "3 + (9-2)" ==> tokens = [3][+][(][9][-][2][)]
String test = "13 + (9-2)";
List<String> allMatches = new ArrayList<String>();
Matcher m = Pattern.compile("\\d+|\\(|\\)|\\+|\\*|-|/")
.matcher(test);
while (m.find()) {
allMatches.add(m.group());
}
Can someone test this please?
I think it would be easiest to read the line into one string, and then split based on space. There is a handy string function split that does this for you.
String[] tokens = input.split("");
It's probably overkill for your example, but in case it gets more complex, take a look at JavaCC, the Java Compiler Compiler. JavaCC allows you to create a parser in Java based on a grammar definition.
Be aware that it is not an easy tool to get started with. However, the grammar definition will be much easier to read than the corresponding regular expressions.
if tokens[] must be String you can use this
String ex="3 + (9-2)";
String tokens[];
StringTokenizer tok=new StringTokenizer(ex);
String line="";
while(tok.hasMoreTokens())line+=tok.nextToken();
tokens=new String[line.length()];
for(int i=1;i<line.length()+1;i++)tokens[i-1]=line.substring(i-1,i);
tokens can be a charArray so:
String ex="3 + (9-2)";
char tokens[];
StringTokenizer tok=new StringTokenizer(ex);
String line="";
while(tok.hasMoreTokens())line+=tok.nextToken();
tokens=line.toCharArray();
This (IMHO elegant) single line of code works (tested):
String[] tokens = input.split("(?<=[^ ])(?<!\\B) *");
This regex also caters for input containing multiple character numbers (eg 123) which would be split into separate characters but for the negative look-behind for a non-word boundary (?<!\\B).
The first look-behind (?<=[^ ]) prevents an initial blank string split at start if input, and assures spaces are consumed.
The final part of the regex " *" assures spaces are consumed.

Splitting a string on the double pipe(||) using String.split()

I'm trying to split the string with double pipe(||) being the delimiter.String looks something like this:
String str ="user#email1.com||user#email2.com||user#email3.com";
i'm able to split it using the StringTokeniser.The javadoc says the use of this class is discouraged and instead look at String.split as option.
StringTokenizer token = new StringTokenizer(str, "||");
The above code works fine.But not able to figure out why below string.split function not giving me expected result..
String[] strArry = str.split("\\||");
Where am i going wrong..?
String.split() uses regular expressions. You need to escape the string that you want to use as divider.
Pattern has a method to do this for you, namely Pattern.quote(String s).
String[] split = str.split(Pattern.quote("||"));
You must escape every single | like this str.split("\\|\\|")
try this bellow :
String[] strArry = str.split("\\|\\|");
You can try this too...
String[] splits = str.split("[\\|]+");
Please note that you have to escape the pipe since it has a special meaning in regular expression and the String.split() method expects a regular expression argument.
For this you can follow two different approaches you can follow whichever suites you best:
Approach 1:
By Using String SPLIT functionality
String str = "a||b||c||d";
String[] parts = str.split("\\|\\|");
This will return you an array of different values after the split:
parts[0] = "a"
parts[1] = "b"
parts[2] = "c"
parts[3] = "d"
Approach 2:
By using PATTERN and MATCHER
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String str = "a||b||c||d";
Pattern p = Pattern.compile("\\|\\|");
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println("Found two consecutive pipes at index " + m.start());
}
This will give you the index positions of consecutive pipes:
parts[0] = "a"
parts[1] = "b"
parts[2] = "c"
parts[3] = "d"
Try this
String yourstring="Hello || World";
String[] storiesdetails = yourstring.split("\\|\\|");

Split()-ing in java

So let's say I have:
String string1 = "123,234,345,456,567*nonImportantData";
String[] stringArray = string1.split(", ");
String[] lastPart = stringArray[stringArray.length-1].split("*");
stringArray[stringArray.length-1] = lastPart[0];
Is there any easier way of making this code work? My objective is to get all the numbers separated, whether stringArray includes nonImportantData or not. Should I maybe use the substring method?
Actually, the String.split(...) method's argument is not a separator string but a regular expression.
You can use
String[] splitStr = string1.split(",|\\*");
where | is a regexp OR and \\ is used to escape * as it is a special operator in regexp. Your split("*") would actually throw a java.util.regex.PatternSyntaxException.
Assuming you always have the format you've provided....
String input = "123,234,345,456,567*nonImportantData";
String[] numbers = input.split("\\*")[0].split(",");
I'd probably remove the unimportant data before splitting the string.
int idx = string1.indexOf('*');
if (idx >= 0)
string1 = string1.substring(0, idx);
String[] arr = string1.split(", ");
If '*' is always present, you can shorten it like this:
String[] arr = str.substring(0, str.indexOf('*')).split(", ");
This is different than MarianP's approach because the "unimportant data" isn't preserved as an element of the array. This may or may not be helpful, depending on your application.

Categories

Resources