Java 为什么不转换所有实例?
我不知道为什么这段代码没有将“m”的所有实例转换为“m”,并将“m”的实例转换为“m”。例如,它应转换为:Java 为什么不转换所有实例?,java,string,replace,Java,String,Replace,我不知道为什么这段代码没有将“m”的所有实例转换为“m”,并将“m”的实例转换为“m”。例如,它应转换为: Report 98-17, Faculty of Technical matheMatics and InforMatics,%:m 2:M 1: Report 98-17, Faculty of Technical MatheMatics and InforMatics,%:m 2:M1: 当它转换为: Report 98-17, Faculty of Technical mathe
Report 98-17, Faculty of Technical matheMatics and InforMatics,%:m 2:M 1:
Report 98-17, Faculty of Technical MatheMatics and InforMatics,%:m 2:M1:
当它转换为:
Report 98-17, Faculty of Technical matheMatics and InforMatics,%:m 2:M 1:
Report 98-17, Faculty of Technical MatheMatics and InforMatics,%:m 2:M1:
谢谢
public static int numberOccurances(String l, char f){
int count=0;
for(int x=0; x<l.length();x++){
if(l.charAt(x)==f)
count++;
}
return count;
}
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
File file = new File("Old.txt");
Scanner scanner = new Scanner(file);
PrintWriter writer = new PrintWriter("New.txt", "UTF-8");
while(scanner.hasNextLine()){
String line = scanner.nextLine();
int numberm=numberOccurances(line, 'm');
int numberM = numberOccurances(line, 'M');
for(int y=0; y<line.length(); y++){
if(line.charAt(y)=='M'){
line=line.substring(0,y) + 'm' + line.substring(y+1);
}
if(line.charAt(y)=='m'){
line=line.substring(0,y) + 'M' + line.substring(y+1);
}
}
if(numberm>0&&numberM>0)
line=line + "%:m " + numberm + ":M" + numberM + ":";
if(numberm>0&&numberM==0)
line=line + "%:m " + numberm + ":";
if(numberM>0&&numberm==0)
line=line + "%:M " + numberM + ":";
writer.println(line);
}
writer.close();
}
公共静态整数精度(字符串l,字符f){
整数计数=0;
对于(int x=0;x0)
行=行+“%:m”+numberm+“:m”+numberm+”:”;
如果(numberm>0&&numberm==0)
行=行+“%:m”+numberm+“:”;
如果(numberM>0&&numberM==0)
行=行+“%:M”+numberM+“:”;
writer.println(行);
}
writer.close();
}
因为您不使用else
,所以当您将M
修改为M
时,第二个if
检测M
并反转效果
所以修改
if(line.charAt(y)=='M'){
line=line.substring(0,y) + 'm' + line.substring(y+1);
}
if(line.charAt(y)=='m'){//pay attention to this line
line=line.substring(0,y) + 'M' + line.substring(y+1);
}
进入
然而,我会推荐一个正则表达式来做这类事情。它使生活更轻松,并将提高性能。因为您不使用
else
,所以当您将M
修改为M
时,如果检测到M
,则第二个,并反转效果
所以修改
if(line.charAt(y)=='M'){
line=line.substring(0,y) + 'm' + line.substring(y+1);
}
if(line.charAt(y)=='m'){//pay attention to this line
line=line.substring(0,y) + 'M' + line.substring(y+1);
}
进入
然而,我会推荐一个正则表达式来做这类事情。它使生活更轻松,并将提高性能