我如何得到一个字符串的最后一个字符?
public class Main {
public static void main(String[] args) {
String s = "test string";
//char lastChar = ???
}
}
我如何得到一个字符串的最后一个字符?
public class Main {
public static void main(String[] args) {
String s = "test string";
//char lastChar = ???
}
}
当前回答
试试这个:
if (s.charAt(0) == s.charAt(s.length() - 1))
其他回答
代码:
public class Test {
public static void main(String args[]) {
String string = args[0];
System.out.println("last character: " +
string.substring(string.length() - 1));
}
}
java Test abcdef的输出:
last character: f
下面是我用来获取字符串的最后n个字符的方法:
public static String takeLast(String value, int count) {
if (value == null || value.trim().length() == 0) return "";
if (count < 1) return "";
if (value.length() > count) {
return value.substring(value.length() - count);
} else {
return value;
}
}
然后像这样使用它:
String testStr = "this is a test string";
String last1 = takeLast(testStr, 1); //Output: g
String last4 = takeLast(testStr, 4); //Output: ring
public char LastChar(String a){
return a.charAt(a.length() - 1);
}
试试这个:
if (s.charAt(0) == s.charAt(s.length() - 1))
下面是一个使用String.charAt()的方法:
String str = "India";
System.out.println("last char = " + str.charAt(str.length() - 1));
结果输出是last char = a。