为什么这不会转换所有实例?

时间:2014-03-11 00:14:10

标签: 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:

感谢。

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();
}

1 个答案:

答案 0 :(得分:4)

因为您没有使用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);
}

if(line.charAt(y)=='M'){
    line=line.substring(0,y) + 'm' + line.substring(y+1);
}
else if(line.charAt(y)=='m'){//pay attention to this line
    line=line.substring(0,y) + 'M' + line.substring(y+1);
}

但是我会推荐一个正则表达式来做这类事情。它使生活更轻松,并将提高性能。