我正在进行另一项编码测试......只是测试了我的一些知识,我在那里遇到了一个尖峰。我知道如何将一个字符串分成一半String.substring
等等......但是我如何分成三分之一?我希望保存到3个字符串," firsthalf" " secondhalf"和" thirdhalf"有人帮帮我吗?
(目前为止的代码):
String text = "abspqrtnf";
String firsthalf = text.substring(0, text.length() / 3);
String secondhalf = text.substring(text.length() / 3);
String thirdhalf = text.substring(text.length() / 3);
答案 0 :(得分:2)
继续你的开始方式:
String text = "abspqrtnf";
int textLength = text.length();
String firsthalf = text.substring(0, textLength / 3);
String secondhalf = text.substring(textLength / 3, text.length() / 3 * 2);
String thirdhalf = text.substring(text.length() / 3 * 2);
答案 1 :(得分:1)
String text = "abspqrtnf";
String firsthalf = text.substring(0, (text.length() / 3));
String secondhalf = text.substring(text.length() / 3,(text.length()*2 / 3));
String thirdhalf = text.substring((text.length()*2 / 3),text.length());
System.out.println(secondhalf + " " +firsthalf + " "+ thirdhalf);
答案 2 :(得分:1)
如上所述,如果字符串长度不能被3整除(截断或更长的最后一个字符串),并且还要满足小于3的输入字符串,则需要决定该怎么做。 建议编写一些单元测试来涵盖这些用例。 下面的一些简单代码作为替代的部分解决方案。
String input = "abcdefghij";
if( input.length() >= 3 )
{
int singleStringLen = input.length() / 3;
int index = singleStringLen;
System.out.println( input.substring( 0, index ) );
System.out.println( input.substring( index, (index += singleStringLen) ) );
// last string maybe longer if input string not divisible by 3
System.out.println( input.substring( index, input.length() ) );
}