在Java中提取字符串的前两个字符 [英] Extract first two characters of a String in Java

查看:43
本文介绍了在Java中提取字符串的前两个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java问题,给出一个字符串,返回由前两个字符组成的字符串,因此字符串"Hello"产生"He".

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".

如果字符串短于长度2,则返回任意长度,因此"X"产生"X",空字符串"产生空字符串".

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

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

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

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?

推荐答案

您的代码看起来很棒!如果要缩短它的长度,可以使用三元运算符:

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

这篇关于在Java中提取字符串的前两个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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