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

前端 未结 8 1909
轮回少年
轮回少年 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:23

    You could easily write such a method, remember that negative indices are subtracted from the length of the string to get the correct index.

    public String slice(String s, int start) {
       if (start < 0) start = s.length() + start; 
    
       return s.substring(start);
    }
    
    0 讨论(0)
  • 2020-12-29 04:24

    Simple answer, no there isn't. Strings are immutable in both languages. Strings are internally stored as character arrays so using substring and using the brackets in Python are essentially doing the same thing. Java doesn't support operator overloading so there's no way to give that functionality to the language. Using substring isn't so bad. You shouldn't have to do it too often. You could always write helper functions if you're doing it very often to simplify your usage.

    0 讨论(0)
提交回复
热议问题