获得两个字符串中最长的一个 [英] Get longest of two string s
本文介绍了获得两个字符串中最长的一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以快速选择两个字符串中的较长者?我想避开要做的事
Is there a quick way to select the longer of two strings? I want to circumvent having to do
if(string1 > string2)
do a;
else if(string2 > string1)
do b;
推荐答案
String have a method length
you can use:
if(string1.length() > string2.length())
do a;
else if(string2.length() > string1.length()
do b;
编辑:我误解了您的问题.这是使用三元运算符
I misunderstood your question. This would be a shorter way to write it using a ternary operator:
String longest = (string1.length() > string2.length()) ? string1 : string2;
我不知道您为什么要寻找一种较短的编写方式,因为与使用三元运算符相比,您的原始方式具有更高的可读性.如果原因是您将多次获得最长的字符串,则建议将比较提取到返回最长字符串的方法中.例如:
I don't know why you are looking for a shorter way to write it since your original way gives much more readability than using a ternary operator. If the reason is that you're going to get the longest string many times I'd recommend to extract the comparison to a method that returns the longest string instead. E.g:
public String getLongestString(String s1, String s2) {
if(s1.length() > s2.length())
return s1;
else
return s2;
}
这篇关于获得两个字符串中最长的一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文