【问题标题】:Get the last three chars from any string - Java从任何字符串中获取最后三个字符 - Java
【发布时间】:2013-03-06 16:57:13
【问题描述】:

我正在尝试获取任何字符串的最后三个字符并将其保存为另一个字符串变量。我的思维过程有些艰难。

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

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

【问题讨论】:

  • 缓冲区是字符所在的char[],索引是要开始复制的那个数组的开始。只需创建一个大小为 3 的 char[] 并将索引设置为 0。虽然 substring 可能会更好
  • 同意mark convert to char[] (String.toCharArray() 然后打印最后3个)

标签: java


【解决方案1】:

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

更新

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

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 fewer than 3 characters!");
}

【讨论】:

  • 可能必须小心少于三个字符的字符串,我认为负输入会返回原始字符串(可能是错误的),这可能会或可能不会被接受努力完成。
  • @celestialorb:负索引会导致异常,根据the docs
  • @celestialorb,感谢您的提及,无论如何,问题中的初始代码也必须处理异常,所以我没有考虑这个问题。
  • 负索引很容易避免使用Math.max() 这样String substr = word.substring(Math.max(0, word.length() - 3));
  • 为什么用问题来回答问题?您不会期望他有不使用子字符串的理由。可能他还不知道。
【解决方案2】:

我会考虑来自 Apache Commons Lang 的 StringUtils 类的 right 方法: http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#right(java.lang.String,%20int)

这是安全的。你不会得到NullPointerExceptionStringIndexOutOfBoundsException

示例用法:

StringUtils.right("abcdef", 3)

您可以在上述链接下找到更多示例。

【讨论】:

    【解决方案3】:

    下面是一些使用正则表达式完成工作的简洁代码:

    String last3 = str.replaceAll(".*?(.?.?.?)?$", "$1");
    

    此代码返回最多 3;如果少于 3 则只返回字符串。

    这是如何在一行中不使用正则表达式的安全

    String last3 = str == null || str.length() < 3 ? 
        str : str.substring(str.length() - 3);
    

    “安全”是指如果字符串为空或短于 3 个字符(所有其他答案都不“安全”),则不会引发异常。


    如果您更喜欢更冗长但可能更易于阅读的形式,上述代码与此代码的效果相同:

    String last3;
    if (str == null || str.length() < 3) {
        last3 = str;
    } else {
        last3 = str.substring(str.length() - 3);
    }
    

    【讨论】:

    • 可能,但由于它的三元运算符和缺少括号,很难理解。所以我建议不要在这里。 -1.
    • @MvG 所以这个答案“没有帮助”? (这就是 -1 投票的含义)。为什么使用三元语法没有帮助?你会把括号放在哪里?相反,我认为这个答案很有帮助,尤其是考虑到如果输入 null 或短输入,所有其他答案都会爆炸。
    • 没有帮助,因为我相信(对不起,如果我错了)大多数在如何从给定字符串中提取子字符串时遇到困难的用户会在试图阅读您的代码时不知所措.检查长度非常好,但在这个级别上,我认为更详细的解决方案很有帮助,而神秘的解决方案只会令人困惑。至于括号:我会写这个… = ((… || …) ? … : …)。您添加的换行也使事情变得更好。
    • 过了很长时间,但仍然想发表评论。 @Bohemian's 是完美的,应该接受答案。
    【解决方案4】:

    String newString = originalString.substring(originalString.length()-3);

    【讨论】:

      【解决方案5】:
      public String getLastThree(String myString) {
          if(myString.length() > 3)
              return myString.substring(myString.length()-3);
          else
              return myString;
      }
      

      【讨论】:

        【解决方案6】:

        如果你想让String由最后三个字符组成,你可以使用substring(int)

        String new_word = word.substring(word.length() - 3);
        

        如果你真的想要它们作为一个字符数组,你应该写

        char[] buffer = new char[3];
        int length = word.length();
        word.getChars(length - 3, length, buffer, 0);
        

        getChars 的前两个参数表示要提取的字符串部分。第三个参数是该部分将被放入的数组。最后一个参数给出了操作开始在缓冲区中的位置。

        如果字符串少于三个字符,则在上述任何一种情况下都会出现异常,因此您可能需要检查一下。

        【讨论】:

          【解决方案7】:

          这是我用来获取字符串最后一个 xx 的方法:

          public static String takeLast(String value, int count) {
              if (value == null || value.trim().length() == 0 || 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
          

          【讨论】:

            【解决方案8】:

            这个方法会很有帮助:

            String rightPart(String text,int length)
            {
                if (text.length()<length) return text;
                String raw = "";
                for (int i = 1; i <= length; i++) {
                    raw += text.toCharArray()[text.length()-i];
                }
                return new StringBuilder(raw).reverse().toString();
            }
            

            【讨论】:

              【解决方案9】:

              getChars 字符串方法不返回值,而是将其结果转储到您的缓冲区(或目标)数组中。 index 参数描述了目标数组中的起始偏移量。

              试试这个link 来更详细地描述getChars 方法。

              我同意其他人的观点,我认为 substring 是处理你想要完成的事情的更好方法。

              【讨论】:

                【解决方案10】:

                你可以使用子字符串

                String word = "onetwotwoone"
                int lenght = word.length(); //Note this should be function.
                String numbers = word.substring(word.length() - 3);
                

                【讨论】:

                • 应该是word.length()
                【解决方案11】:

                “字符串长度不足或为空”的另一种保存方式:

                String numbers = defaultValue();
                try{
                   numbers = word.substring(word.length() - 3);
                } catch(Exception e) {
                   System.out.println("Insufficient String length");
                }
                

                【讨论】:

                • 请不要提供“仅代码”的答案。它可能无法帮助其他找到此帖子的人。请简要说明您的代码在做什么以及为什么它有助于解决 OP 的问题。
                • 完成 Mike...如果需要,请随时改进。
                【解决方案12】:

                此方法将返回从末尾开始的 x 个字符。

                public static String lastXChars(String v, int x) {
                    return v.length() <= x ? v : v.substring(v.length() - x);
                }
                

                //用法

                System.out.println(lastXChars("stackoverflow", 4)); // flow
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-09-18
                  • 2013-03-17
                  • 2011-03-29
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-07-07
                  相关资源
                  最近更新 更多