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

前端 未结 8 1931
轮回少年
轮回少年 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条回答
  •  無奈伤痛
    2020-12-29 04:07

    I think there is no such Java string library providing exactly the same thing provided by python. Probably the best you can do is to build a new class which provides the functions you need. Since the String in java is a final class which you cannot have a class extend from it, you need to use composition. For example:

    public class PythonString {
      protected String value;
      public PythonString(String str) {
        value = new String(str);
      }
    
      public char charAt(int index) {
        if (index < 0) {
          return value.charAt(value.length() + index);
        }
        return value.charAt(index);
      }
    
      ....
    
    }
    

    Another alternative is to create a static string library.

提交回复
热议问题