简体   繁体   中英

How can I only append only once per line that has a replacement?

I am having trouble just adding "%:" to the lines that replacements occur on. This program goes through the whole alphabet and converts all lower-case letters to upper-case, and upper-case to lower-case. Then, at the end of the file, it is supposed to add

"%: a: x:b: y....z: z"

where x,y,and z are how many replacements occur on each line. How can I only add the "%:" to lines that have replacements? And also note that there is only one "%:" per line if there is a replacement. Thanks.

    File file = new File("old.tex");
    Scanner scanner = new Scanner(file);
    PrintWriter writer = new PrintWriter("new.tex");
    while(scanner.hasNextLine()){
        int numberlc;
        int numberuc;
    String line = scanner.nextLine();
    line=line+ "%:";
    for(char ch='a';ch<='z';ch++){
        numberlc=numberOccurances(line, ch);
        char upperch=Character.toUpperCase(ch);
        numberuc=numberOccurances(line, upperch);
        for(int y=0; y<line.length(); y++){
            if(line.charAt(y)==ch)
                line=line.substring(0,y) + upperch + line.substring(y+1);
            else if(line.charAt(y)==upperch)
                line=line.substring(0,y) + ch + line.substring(y+1);
        }
        if(numberlc>0)
            line=line + ch + " " + numberlc + ":";
        if(numberuc>0)
            line=line + upperch + " " + numberuc + ":";
    }
    writer.println(line);
}
writer.close()

I'd suggest keeping your additions separate until you are finished with the line.

Something like this:

StringBuilder changes = new StringBuilder("%: ");
for(char ch='a';ch<='z';ch++){
    numberlc=numberOccurances(line, ch);
    char upperch=Character.toUpperCase(ch);
    numberuc=numberOccurances(line, upperch);
    for(int y=0; y<line.length(); y++){
        if(line.charAt(y)==ch)
            line=line.substring(0,y) + upperch + line.substring(y+1);
        else if(line.charAt(y)==upperch)
            line=line.substring(0,y) + ch + line.substring(y+1);
    }
    if(numberlc>0)
        changes.append(ch + " " + numberlc + ":");
    if(numberuc>0)
        changes.append(upperch + " " + numberuc + ":");
}
if (changes.length() > 3)
    line += changes.toString();
writer.println(line);

Note: This code isn't tested

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM