Given:
public class StringSplit01 {
public static void main(String[] args) {
String names = “John-.-George-.-Paul-.-Ringo”;
String[] results = names.split(“-. .”);
for(String str:results) {
System.out.println(str);
}
}
}
What is the result?
A.
John – . – George – . – Paul – . – Ringo
B.
John
George
Paul
Ringo
C.
John –
George –
Paul –
Ringo –
D.
An exception is thrown at runtime
E.
Compilation fails
Explanation:
The split() method is used to split a string into an array of substrings, and returns the new array.
It’s A)
For B) it should be:
String[] results = names.split(“-.-“);
Thanks.
to be more precise the dot “.” matches any character
it should be restricted to \p that identifies a puncutation char or (if it works) i dont remeber \.
No that’s wrong sir, -.. here . stands for any character if u need . use \\. u have to check regex one more time
Answer is B
. Any character (may or may not match line terminators)
Answer is B.
String[] results = names.split(“-..”); => Answer is B
[exec:exec]
John
George
Paul
Ringo
String[] results = names.split(“-. .”);(we have space between points) => Answer is A
[exec:exec]
John-.-George-.-Paul-.-Ringo
It can’t never be Answer A, because of spaces between dots and strokes in the output which are not present in source-string.
source: John-.-George-.-Paul-.-Ringo
output: John – . – George – . – Paul – . – Ringo
Maybe for a better readability, who knows. Maybe thats the reason too for the space-character in the redex. If you leave this like “-..”, then the answer is B.
Just tested it.
String[] results = names.split(“-..”); => Answer is B (thanks Serg).
String[] results = names.split(“-. .”);(we have space between points) => None of the options are correct (thanks Jan).
My tests:
String[] results = names.split(“-. .”); –> Answer A
Output:
John-.-George-.-Paul-.-Ringo
String[] results = names.split(“-..”); –> Answer B
Output:
John
George
Paul
Ringo
Answer A:
The split method didn’t split nothing, because the regex “-. .” can’t be find in the names String, so it is printed the original String
I’m considering that the answer A is this:
John–.–George–.–Paul–.–Ringo (withous spaces, like the original names String)
a
b
I’ve seen this question before. There are supposed to be no spaces in the regex expression, so it’s like this “-..”, which means a dash followed by any two characters.
So the correct answer is B.