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
Related
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 have following string
String str="aaaaaaaaa\n\n\nbbbbbbbbbbb\n \n";
I want to break it on \n so at the end i should two string aaaaaaaa and bbbbbbbb. I dont want last one as it only contain white space. so if i split it based on new line character using str.split() final array should have two entry only.
I tried below:
String str="aaaaaaaaa\n\n\nbbbbbbbbbbb\n \n".replaceAll("\\s+", " ");
String[] split = str.split("\n+");
it ignore all \n and give single string aaaaaaaaaa bbbbbbbb.
Delete the call to replaceAll(), which is removing the newlines too. Just this will do:
String[] split = str.split("\n\\s*");
This will not split on just spaces - the split must start at a newline (followed by optional further whitespace).
Here's some test code using your sample input with edge case enhancement:
String str = "aaaaaaaaa\nbbbbbb bbbbb\n \n";
String[] split = str.split("\n\\s*");
System.out.println(Arrays.toString(split));
Output:
[aaaaaaaaa, bbbbbb bbbbb]
This should do the trick:
String str="aaaaaaaaa\n\n\nbbbbbbbbbbb\n \n";
String[] lines = str.split("\\s*\n\\s*");
It will also remove all trailing and leading whitespace from all lines.
The \ns are removed by your first statement: \s matches \n
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'm getting user input that I need to format. I need to remove all leading/trailing spaces and I need to capitalize the first letter of each word.
Here is what I'm trying, however... if you input something with 2 spaces between words, it crashes. How might I solve this?
String formattedInput = "";
String inputLineArray[] = inputLine.getText().toString().trim().split("\\s");
for (int d=0; d<inputLineArray.length; d++) {
formattedInput = formattedInput.trim() + " " +
inputLineArray[d].trim().substring(0,1).toUpperCase() +
inputLineArray[d].trim().substring(1).toLowerCase();
}
Your code is blowing up on multiple spaces because when you split you're getting a member in your array that is an empty string "hello there" when split becomes array[0] = "hello", array[1] = "", array[2] = "there".
So when you do substring(0,1) you should get an IndexOutOfBoundsException.
Try changing your split("\\s") to split("\\s+") this way your multiple spaces get picked up in the regex and thrown out.
Edit:
This also will let you get rid of the .trim() inside your loop since all of the spaces will be taken care of by the split.
tokenize the string and split by space " " and then take each iteration and capitalize it and then put it back together again
read all about string tokenization here