How do I get the last character of a string?

前端 未结 11 2231
遥遥无期
遥遥无期 2020-12-02 07:59

How do I get the last character of a string?

public class Main {
    public static void main(String[] args)  {
        String s = "test string";
            


        
11条回答
  •  忘掉有多难
    2020-12-02 08:55

    Simple solution is:

    public String frontBack(String str) {
      if (str == null || str.length() == 0) {
        return str;
      }
      char[] cs = str.toCharArray();
      char first = cs[0];
      cs[0] = cs[cs.length -1];
      cs[cs.length -1] = first;
      return new String(cs);
    }
    

    Using a character array (watch out for the nasty empty String or null String argument!)

    Another solution uses StringBuilder (which is usually used to do String manupilation since String itself is immutable.

    public String frontBack(String str) {
      if (str == null || str.length() == 0) {
        return str;
      }
      StringBuilder sb = new StringBuilder(str);  
      char first = sb.charAt(0);
      sb.setCharAt(0, sb.charAt(sb.length()-1));
      sb.setCharAt(sb.length()-1, first);
      return sb.toString();
    }
    

    Yet another approach (more for instruction than actual use) is this one:

    public String frontBack(String str) {
      if (str == null || str.length() < 2) {
        return str;
      }
      StringBuilder sb = new StringBuilder(str);
      String sub = sb.substring(1, sb.length() -1);
      return sb.reverse().replace(1, sb.length() -1, sub).toString();
    }
    

    Here the complete string is reversed and then the part that should not be reversed is replaced with the substring. ;)

提交回复
热议问题