如何进行Java(Android)字符串替换?
我不明白为什么这不起作用: (方法取材于SO)如何进行Java(Android)字符串替换?,java,android,string,substitution,string-substitution,Java,Android,String,Substitution,String Substitution,我不明白为什么这不起作用: (方法取材于SO) 私有字符串使SizeHumanReadable(整数字节,布尔si){ 整数单位=si?1000:1024; 如果(字节
私有字符串使SizeHumanReadable(整数字节,布尔si){
整数单位=si?1000:1024;
如果(字节<单位)返回字节+“B”;
int exp=(int)(Math.log(字节)/Math.log(单位));
字符串pre=(si?“kMGTPE”:“kMGTPE”).charAt(exp-1)+(si?“:“i”);
字符串hr=String.format(“%.1f%sB”,字节/Math.pow(单位,exp),pre);
hr=hr.替换(“-1 B”,“n.a.”);
返回人力资源;
}
这两个都不是:-
private String MakeSizeHumanReadable(int bytes, boolean si) {
int unit = si ? 1000 : 1024;
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
String hr = String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
Pattern minusPattern = Pattern.compile("-1 B");
Matcher minusMatcher = minusPattern.matcher(hr);
if (minusMatcher.find()) {
return "n.a.";
} else {
return hr;
}
}
私有字符串使SizeHumanReadable(整数字节,布尔si){
整数单位=si?1000:1024;
如果(字节<单位)返回字节+“B”;
int exp=(int)(Math.log(字节)/Math.log(单位));
字符串pre=(si?“kMGTPE”:“kMGTPE”).charAt(exp-1)+(si?“:“i”);
字符串hr=String.format(“%.1f%sB”,字节/Math.pow(单位,exp),pre);
Pattern=Pattern.compile(“-1b”);
匹配器minusMatcher=minusPattern.Matcher(hr);
if(minusMatcher.find()){
返回“不适用”;
}否则{
返回人力资源;
}
}
我不时从请求中得到-1b
(这是正常的),这在n.a.
(……我的问题)中从未改变过
有人有想法吗?这是你的问题:
if (bytes < unit) return bytes + " B";
if(bytes
当字节
等于-1(在任何一种情况下都小于单位
时,它返回-1b
,而从未到达行hr=hr。替换(“-1b”,“n.a.”)代码>
最好在末尾有一个return
语句,在if
中分配字符串hr=bytes+“B”
,并在接下来的三行周围添加一个else
块。然后,在该块之后,hr.replace()
调用将以任何方式执行,然后返回值。请考虑首先准确地告诉我们您试图使用此代码执行的操作。谢谢负1。我刚才正在编辑以添加来自SO的链接。你跑得很快。无论如何,这一行我从请求中不时得到-1b(这是正常的),这在n.a.(…我的问题)中从未改变过。
解释说我想改变-1b
从n.a.
中的链接方法返回的值,这很公平。我在想,这两个块的共同代码在某种程度上解释了这一点。我现在要试试。谢谢我不知道为什么我没有收到你回复的邮件通知!
if (bytes < unit) return bytes + " B";