String Split method not Giving desired results [duplicate] - java

This question already has answers here:
Java string split with "." (dot) [duplicate]
(4 answers)
Closed 7 years ago.
I am trying to use Split method of String in java I have example like this.
String number = Math.random() * 100 + "";
System.out.println("Number is : " + number);
String[] seprate = number.split(".");
System.out.println(seprate.length);
it should give me 2 Stack of array i mean 2 array element if value is like e.g. 67.90512897385857
but its not giving value like that
String number = Math.random() * 100 + "";
System.out.println("Number is : " + number);
String[] seprate = number.split(".");
System.out.println(seprate.length);
System.out.println(seprate[1]);
its giving arrayindexoutbound exception.
Someone give idea why its giving like that?

The String#split method takes a regular expression.
The "." in there means any character.
Escape your "." as such to signal a literal dot: number.split("\\.").
As Pieter De Bie points out, using java.util.regex.Pattern to safely escape your literals when passing literals to an argument that is going to be interpreted as a regular expression will help you a good deal.
In this case, you could use: number.split(Pattern.quote("."))

You need to escape the dot. The split method takes a regular expression. From the docs:
Parameters:regex the delimiting regular expression
String[] seprate = number.split("\\.");

Split works with regex and you should use like this
number.split("\\.")

Pay attention to the documentation:
public String[] split(String regex)
Splits this string around matches of the given regular expression.
In a regular expression, . is any character (except newlines, usually).
So you are splitting at every character.
If you want to match only a dot, "\\." will work.

Double f = Math.random() * 100;
String number = String.valueOf(f);
System.out.println("Number is : " + number);
String[] seprate = number.split("\\.");
System.out.println(seprate.length);
Please use this link for ur question.
The split() method in Java does not work on a dot (.)

Related

Split a word by a char in Java [duplicate]

This question already has answers here:
How to split a string, but also keep the delimiters?
(24 answers)
How do I split a string in Java?
(39 answers)
Closed 3 years ago.
Consider the following example. I would like to divide the String into two parts by the char 'T'
// input
String toDivideStr = "RaT15544";
// output
first= "RaT";
second = "15544";
I've tried this:
String[] first = toDivideStr.split("T",0);
Output:
first = "Ra"
second = "15544"
How do I achieve this?
What you need to to, is locate the last "T", then split:
StringToD.substring(StringToD.lastIndexOf("T") + 1)
You could use a positive lookahead to assert a digit and a positive lookbehind to assert RaT.
(?<=RaT)(?=\\d)
For example:
String str = "RaT15544";
for (String element : str.split("(?<=RaT)(?=\\d)"))
System.out.println(element);
Regex demo | Java demo
You can use positive look-ahead with split limit parameter for this. (?=\\d)
With only T in the split method parameter, what happens is the regex engine consumes this T. Hence the two string split that occurs doesn't have T. To avoid consuming the characters, we can use non-consumeing look-ahead.
(?=\\d) - This will match the first number that is encountered but it will not consume this number
public static void main(String[] args) {
String s = "RaT15544";
String[] ss = s.split("(?=\\d)", 2);
System.out.println(ss[0] + " " + ss[1]);
}
The below regex can be used to split the alphabets and numbers separately.
String StringToD = "RaT15544";
String[] parts = StringToD.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
System.out.println(parts[0]);
System.out.println(parts[1]);

What can I add to this regex to make it also seperate the string by an underscore in Java?

So I have this regex that does what I need it to for the most part, or so I thought..
String[] part = str.split("\\b");
This will take a string such as " int(x,y) " and separate it into 6 new strings.
1. int
2. (
3. x
4. ,
5. y
6. )
BUT I just realized that my regex is not doing this with underscores? For example the string " ret_urn" is not split at all. Is it possible to add an "AND" to my regex to include underscores?
You can use something like below to get the result you expect with an or,
String str = "int(x,y)_ret_urn";
str.split("\\b|((?<=_)|(?=_))");

String.split() not working with "[]" [duplicate]

This question already has answers here:
Why can't I split a string with the dollar sign?
(6 answers)
Closed 7 years ago.
I have a IPv6 string
String str = "demo1 26:11:d0a2:f020:0:0:0:a3:2123 demo2";
String searchString = "26:11:d0a2:f020:0:0:0:a3:2123";
When i use str.split(searchString) code returns
["demo1 ", " demo2"]
Which is fine but when i use:
String str = "demo1 [26:11:d0a2:f020:0:0:0:a3]:2123 demo2";
String searchString = "[26:11:d0a2:f020:0:0:0:a3]:2123";
and do str.split(searchString) it reutrns
[demo1 [26:11:d0a2:f020:0:0:0:a3]:2123 demo2]
Which is wrong i guess , can some one tell why I am getting this sort of output?
Since split function takes a regex as parameter, you need to escape those brackets otherwise this [26:11:d0a2:f020:0:0:0:a3] would match a single character only.
String searchString = "\\[26:11:d0a2:f020:0:0:0:a3\\]:2123";
str.split(searchString);
It is happening because split(String str) take regex pattern string as argument. And that string will be used as regex pattern to match all the delimiter with this pattern.
In your regex pattern you are providing character sets in [].
To make it work your way you will have to use this regex pattern string :
\[26:11:d0a2:f020:0:0:0:a3\]:2123
i.e. in java :
String searchString = "\\[26:11:d0a2:f020:0:0:0:a3\\]:2123";
I hope you are familiar with the string regexs. In java, the regex [abc] means match with a OR b OR c I encourage you to escape your square brackets try:
String str = "demo1 [26:11:d0a2:f020:0:0:0:a3]:2123 demo2";
String searchString = "\\[26:11:d0a2:f020:0:0:0:a3\\]:2123";
You have to use an escape sequence for some special characters. Use \\[ ... \\] in the searchString variable.

having trouble with arrays and maybe split

String realstring = "&&&.&&&&";
Double value = 555.55555;
String[] arraystring = realstring.split(".");
String stringvalue = String.valueof(value);
String [] valuearrayed = stringvalue.split(".");
System.out.println(arraystring[0]);
Sorry if it looks bad. Rewrote on my phone. I keep getting ArrayIndexOutOfBoundsException: 0 at the System.out.println. I have looked and can't figure it out. Thanks for the help.
split() takes a regexp as argument, not a literal string. You have to escape the dot:
string.split("\\.");
or
string.split(Pattern.quote("."));
Or you could also simply use indexOf('.') and substring() to get the two parts of your string.
And if the goal is to get the integer part of a double, you could also simply use
long truncated = (long) doubleValue;
split uses regex as parameter and in regex . means "any character except line separators", so you could expect that "a.bc".split(".") would create array of empty strings like ["","","","",""]. Only reason it is not happening is because (from split javadoc)
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
so because all strings are empty you get empty array (and that is because you see ArrayIndexOutOfBoundsException).
To turn off removal mechanism you would have to use split(regex, limit) version with negative limit.
To split on . literal you need to escape it with \. (which in Java needs to be written as "\\." because \ is also Strings metacharacter) or [.] or other regex mechanism.
Dot (.) is a special character so you need to escape it.
String realstring = "&&&.&&&&";
String[] partsOfString = realstring.split("\\.");
String part1 = partsOfString[0];
String part2 = partsOfString[1];
System.out.println(part1);
this will print expected result of
&&&
Its also handy to test if given string contains this character. You can do this by doing :
if (string.contains(".")) {
// Split it.
} else {
throw new IllegalArgumentException("String " + string + " does not contain .");
}

Java String.split error

My method successfully takes a binary expression tree and turns it into prefix, postfix, and infix notation. However, due to the accuracy of the final string, it must be exactly equal.
So before I return my output, I will run a method to quickly edit that output to remove any flaws.
(* (+ 8 4) (- 7 (/ 6 3))) ===> (*(+ 8 4)(- 7(/ 6 3)))
((8 4 +) (7 (6 3 /) -) ) =====> ((8 4 +)(7 (6 3 /)-))
What needs to be changed, are the spacing inbetween parens. My goal was to find all cases of a string, remove them, and reinput in the string without spaces.
underlines are extra spaces
(*(+ 8 4)(- 7_(/ 6 3)))
My code was supposted to be String.split(") ("); but error signs... unmatched closing ')')(???
public String antibullshiter(String out) {
out = out.replaceFirst(") (", "X"); //edited
String[] parts = out.split("X");
String part1 = parts[0];
String part2 = parts[1];
part1 = part1 + ")";
part2 = part2 + "(";
out = part1 + part2;
return out;}
How do I harness the power of String.split()?
edit: thanks guys, but I realized I just had to deal with the primary method in itself
As mentioned in the other answers / comments, String.split takes a pattern string (regular expression), and that's why you're getting the unmatched parenthesis error. You can use the Pattern.quote method to get the pattern string that would match your string literal:
yourString.split(java.util.regex.Pattern.quote(") ("));
As, String is immutable. To got the changes of replaceFirst method, you need to re-assign with out. Also you need to skip the Meta Character.
out=out.replaceFirst("\\)\\s*\\(", "X");
Try this. It replaces the string.
out.replaceFirst("\\) \\(", "X");
You can use this regular expression to remove spaces surrounding parenthesis:
out=out.replaceAll("\\s*([()])\\s*", "$1");
Use s.replaceAll("(?<=\\))\\s(?=\\()","") to remove the spaces
the error is because the string is a regex string, and parenteses must be escaped with double backslash ("\\(") otherwise they have special meaning.
Edit: use s.replaceAll("(?<=\\))\\s+(?=\\()","") for multiple spaces

Categories