我正在创建一个简单的程序来将二进制数转换为十六进制,而不使用Java提供的方法来完成此操作。我已经有了大部分代码,只是我的“拆分字符串”方法有点问题。
基本上,我在这个方法中想要做的就是
1)接受一个字符串(二进制数)
2)创建一个字符串数组来保存数字的“分组”
3)将二进制数分成4位一组(例如10011101 = 1001,1101)
4)返回分组数组
然而,当使用我的方法时,我的"groupings“数组中的第一个元素总是只有3。(例如,应该是"1001",但只放"100")。我在这里做错了什么?
public String[] splitIntoFours (String toSplit) {
int stringPart = 4;
int arraySize = toSplit.length() / 4;
String[] groupings = new String[arraySize];
for (int iterator = 0; (iterator * stringPart) < toSplit.length(); iterator++){
//If statement to deal with the inital case of the iterator being 0,
//where this algorithm only takes the first 3 numbers instead of a
//sequence of 4 numbers.
int start = iterator * stringPart;
int end = start + stringPart;
if (end > toSplit.length()) {
end = toSplit.length();
}
groupings[iterator] = toSplit.substring(start, end);
}
return groupings;
}发布于 2012-01-28 00:24:53
请记住,子字符串不会返回由end表示的索引处的字符。它返回end-1。
Javadoc和extract
公共字符串子字符串( int beginIndex,int endIndex)
返回一个新字符串,它是此字符串的子字符串。子字符串从指定的索引开始,延伸到索引endIndex - 1处的字符。因此,子字符串的长度为endIndex-beginIndex。
示例:
"hamburger".substring(4,8)返回“敦促”
"smiles".substring(1,5)返回“英里”
发布于 2012-01-28 00:23:55
String.substring中的第二个参数(endIndex)是独占的,请仔细查看文档中的示例。
发布于 2012-01-28 00:27:26
复制这段代码并运行它,它就能正常工作。所以这是没有问题的。使用可被4整除的String.length的输出是正确的。
https://stackoverflow.com/questions/9036550
复制相似问题