在 Java 中提取字符串的前两个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42217815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:00:49  来源:igfitidea点击:

Extract first two characters of a String in Java

javastringcomputer-science

提问by Allen Li

I got a java question which is Given a string, return the string made of its first two chars, so the String "Hello" yields "He".

我有一个 java 问题,它是给定一个字符串,返回由它的前两个字符组成的字符串,因此字符串“Hello”产生“He”。

If the string is shorter than length 2, return whatever there is, so "X" yields "X", and the empty string "" yields the empty string "".

如果字符串比长度 2 短,则返回任何存在的内容,因此“X”产生“X”,而空字符串“”产生空字符串“”。

Note that str.length()returns the length of a string.

请注意,str.length()返回字符串的长度。

public String firstTwo(String str) {          

 if(str.length()<2){
     return str;
 }
 else{
     return str.substring(0,2);
 }
}

I'm wondering is there any other way can solve this question?

我想知道有没有其他方法可以解决这个问题?

采纳答案by Andrew Jenkins

Your code looks great! If you wanted to make it shorter you could use the ternary operator:

你的代码看起来很棒!如果你想让它更短,你可以使用三元运算符

public String firstTwo(String str) {
    return str.length() < 2 ? str : str.substring(0, 2);
}