Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (920 points)

I am using the String split method and I want to have the last element. The size of the Array can change.

Example:

String one = "Düsseldorf - Zentrum - Günnewig Uebachs"
String two = "Düsseldorf - Madison"

I want to split the above Strings and get the last item:

lastone = one.split("-")[here the last item] // <- how?
lasttwo = two.split("-")[here the last item] // <- how?

I don't know the sizes of the arrays at runtime :(

1 Answer

0 votes
by (13.2k points)
  1. lastIndexOf()

String[] bits = one.split("-");

String lastOne = bits[bits.length-1];

  1. length

String last = string.substring(string.lastIndexOf('-') + 1);

Related questions

0 votes
1 answer
asked Jul 18, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer
asked Sep 30, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Jul 26, 2019 in Java by Shubham (3.9k points)

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...