What is the result?

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?

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.



Leave a Reply 15

Your email address will not be published. Required fields are marked *


Julia

Julia

It’s A)
For B) it should be:

String[] results = names.split(“-.-“);

Francesco

Francesco

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 \.

Bahaa Khateib

Bahaa Khateib

No that’s wrong sir, -.. here . stands for any character if u need . use \\. u have to check regex one more time

Ray

Ray

Answer is B
. Any character (may or may not match line terminators)

Charlie

Charlie

Answer is B.

Serg

Serg

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

Jan

Jan

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.

Tim

Tim

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).

Luiz

Luiz

My tests:

String[] results = names.split(“-. .”); –> Answer A
Output:
John-.-George-.-Paul-.-Ringo

String[] results = names.split(“-..”); –> Answer B
Output:
John
George
Paul
Ringo

Luiz

Luiz

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

Luiz

Luiz

I’m considering that the answer A is this:

John–.–George–.–Paul–.–Ringo (withous spaces, like the original names String)

Dylan

Dylan

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.