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

前端 未结 8 1935
轮回少年
轮回少年 2020-12-29 03:24

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]
>>> \"hell         


        
8条回答
  •  旧时难觅i
    2020-12-29 04:18

    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.

提交回复
热议问题