Alex Rivera | Logout

Is there a Java equivalent to Python's Easy String Splicing?

Asked 2013-06-25T21:21:47.760
30

Ok, what I want to know is is there a way with Java to do what Python can do below...

string_sample = "hello world"

string_sample[:-1]
>>> "hello world"

string_sample[-1]
>>> "d"

string_sample[3]
>>> "l"

Because it seems to me that Java make you work for the same result (I'm particularly getting at having to use 2 numbers every time and the lack of a -1 to indicate last character)

String string_sample = "hello world";

string_sample.substring(0,string_sample.length()-1);
>>> "hello world"

string_sample.substringstring_sample.length()];
>>> "d"

string_sample.(3,4);
>>> "l"

I haven't gotten on to arrays/lists yet in Java so really hoping Java has something easier than this

Edit: Ammended 'i' to 'l' for string_sample[3]. Well spotted Maroun!

Edit
Report

1 Answer

1

use substring:

class Main
{
  public static void main (String[] args) throws java.lang.Exception
  {
     String s = new String("hello world");
     System.out.println(s.substring(0, s.length()));
     System.out.println(s.substring(s.length() - 1, s.length()));
     System.out.println(s.substring(3, 4));
  }
}

or charAt:

System.out.println(s.charAt(s.length() - 1));
System.out.println(s.charAt(3));

Java is not python so negative index should be avoided to maintain constancy. However, you could make a simple conversion function.

answered 2013-06-25T21:29:19.103

Your Answer