从任何字符串中获取最后三个字符-Java [英] Get the last three chars from any string - Java

查看:103
本文介绍了从任何字符串中获取最后三个字符-Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取任何字符串的最后三个字符,并将其另存为另一个String变量.我的思考过程很艰难.

I'm trying to take the last three chracters of any string and save it as another String variable. I'm having some tough time with my thought process.

String word = "onetwotwoone"
int length = word.length();
String new_word = id.getChars(length-3, length, buffer, index);

当涉及到缓冲区或索引时,我不知道如何使用getChars方法.Eclipse使我拥有这些功能.有什么建议吗?

I don't know how to use the getChars method when it comes to buffer or index. Eclipse is making me have those in there. Any suggestions?

推荐答案

为什么不只是 String substr = word.substring(word.length()-3)?

更新

在调用 substring()之前,请确保您检查 String 的长度至少为3个字符:

Please make sure you check that the String is at least 3 characters long before calling substring():

if (word.length() == 3) {
  return word;
} else if (word.length() > 3) {
  return word.substring(word.length() - 3);
} else {
  // whatever is appropriate in this case
  throw new IllegalArgumentException("word has less than 3 characters!");
}

这篇关于从任何字符串中获取最后三个字符-Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆