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.
Related
I have a string with signs and i want to get the signs only and put them in a string array, here is what I've done:
String str = "155+40-5+6";
// replace the numbers with spaces, leaving the signs and spaces
String signString = str.replaceAll("[0-9]", " ");
// then get an array that contains the signs without spaces
String[] signsArray = stringSigns.trim().split(" ");
However the the 2nd element of the signsArray is a space, [+ , , -, +]
Thank you for your time.
You could do this a couple of ways. Either replace multiple adjacent digits with a single space:
// replace the numbers with spaces, leaving the signs and spaces
String signString = str.replaceAll("[0-9]+", " ");
Or alternatively in the last step, split on multiple spaces:
// then get an array that contains the signs without spaces
String[] signsArray = signString.trim().split(" +");
Just replace " " to "" in your code
String str = "155+40-5+6";
// replace the numbers with spaces, leaving the signs and spaces
String signString = str.replaceAll("[0-9]","");
// then get an array that contains the signs without spaces
String[] signsArray = stringSigns.split("");
This should work for you. Cheers
Image of running code
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
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 have strings in the following form:
let the character - denote empty space
----100----100----1000---
that is, more empty spaces followed by a number, followed by more empty spaces followed by number, etc.
I need to extract the three numbers only. How do I do that in java?
Thanks
I need to extract the three numbers only. How do I do that in java?
So I understand your string is like below, in which case you can split it on white spaces:
String str = " 100 100 1000";
String[] numbers = str.trim().split("\\s+");
To collapse the spaces (the question asked):
String collapsed = str.replaceAll(" +", " ");
To extract the 3 numbers (the question alluded to):
String[] numbers = str.trim().split(" +");
simply try using,
String newstring = oldstring.replaceAll(" +", " ");
or
String[] selected = oldstring.trim().split(" +");
I am trying to use a simple split to break up the following string: 00-00000
My expression is: ^([0-9][0-9])(-)([0-9])([0-9])([0-9])([0-9])([0-9])
And my usage is:
String s = "00-00000";
String pattern = "^([0-9][0-9])(-)([0-9])([0-9])([0-9])([0-9])([0-9])";
String[] parts = s.split(pattern);
If I play around with the Pattern and Matcher classes I can see that my pattern does match and the matcher tells me my groupCount is 7 which is correct. But when I try and split them I have no luck.
String.split does not use capturing groups as its result. It finds whatever matches and uses that as the delimiter. So the resulting String[] are substrings in between what the regex matches. As it is the regex matches the whole string, and with the whole string as a delimiter there is nothing else left so it returns an empty array.
If you want to use regex capturing groups you will have to use Matcher.group(), String.split() will not do.
for your example, you could simply do this:
String s = "00-00000";
String pattern = "-";
String[] parts = s.split(pattern);
I can not be sure, but I think what you are trying to do is to get each matched group into an array.
Matcher matcher = Pattern.compile(pattern).matcher();
if (matcher.matches()) {
String s[] = new String[matcher.groupCount()) {
for (int i=0;i<matches.groupCount();i++) {
s[i] = matcher.group(i);
}
}
}
From the documentation:
String[] split(String regex) -- Returns: the array of strings computed by splitting this string around matches of the given regular expression
Essentially the regular expression is used to define delimiters in the input string. You can use capturing groups and backreferences in your pattern (e.g. for lookarounds), but ultimately what matters is what and where the pattern matches, because that defines what goes into the returned array.
If you want to split your original string into 7 parts using regular expression, then you can do something like this:
String s = "12-3456";
String[] parts = s.split("(?!^)");
System.out.println(parts.length); // prints "7"
for (String part : parts) {
System.out.println("Part [" + part + "]");
} // prints "[1] [2] [-] [3] [4] [5] [6] "
This splits on zero-length matching assertion (?!^), which is anywhere except before the first character in the string. This prevents the empty string to be the first element in the array, and trailing empty string is already discarded because we use the default limit parameter to split.
Using regular expression to get individual character of a string like this is an overkill, though. If you have only a few characters, then the most concise option is to use foreach on the toCharArray():
for (char ch : "12-3456".toCharArray()) {
System.out.print("[" + ch + "] ");
}
This is not the most efficient option if you have a longer string.
Splitting on -
This may also be what you're looking for:
String s = "12-3456";
String[] parts = s.split("-");
System.out.println(parts.length); // prints "2"
for (String part : parts) {
System.out.print("[" + part + "] ");
} // prints "[12] [3456] "