How do I get the last character of a string?

2019-01-13 00:03发布

How do I get the last character of a string?

public class Main
{
    public static void main(String[] args) 
    {
        String s = "test string";
        //char lastChar = ???
    }   
}

10条回答
我命由我不由天
2楼-- · 2019-01-13 00:24
public char LastChar(String a){
    return a.charAt(a.length() - 1);
}
查看更多
别忘想泡老子
3楼-- · 2019-01-13 00:25

Here is a method using String.charAt():

String str = "India";
System.out.println("last char = " + str.charAt(str.length() - 1));

The resulting output is last char = a.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-13 00:27

The other answers are very complete, and you should definitely use them if you're trying to find the last character of a string. But if you're just trying to use a conditional (e.g. is the last character 'g'), you could also do the following:

if (str.endsWith("g")) {

or, strings

if (str.endsWith("bar")) {
查看更多
倾城 Initia
5楼-- · 2019-01-13 00:29

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. ;)

查看更多
登录 后发表回答