272 - TEX Quotes

11:58 AM | , , , ,

You are to write a program which converts text containing double-quote (") characters into text that is identical except that double-quotes have been replaced by the two-character sequences required by TeX for delimiting quotations with oriented double-quotes. The double-quote (") characters should be replaced appropriately by either `` if the " opens a quotation and by '' if the " closes a quotation. Notice that the question of nested quotations does not arise: The first " must be replaced by ``, the next by '', the next by ``, the next by '', the next by ``, the next by '', and so on. 
Input will consist of several lines of text containing an even number of double-quote (") characters. Input is ended with an end-of-file character. The text must be output exactly as it was input except that:

  • the first " in each pair is replaced by two ` characters: `` and
  • the second " in each pair is replaced by two ' characters: ''.
For this problem , you can try to resolve with this algorithm
  1. First of all you must identify an EOF input scanner
  2. Split string into some substring, for example i try with loop one by one (if you know better you can use it)
  3. Identify a variable as a sign of the first pair  or the second one , i use a boolean variable
  4. Test substring if contains " (double quoted) and replace them with `` for the first and '' for the second
Here is a complete source with java

import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        Scanner inp=new Scanner(System.in);
        boolean ganjil=true;
        while(inp.hasNext()){
            String str=inp.nextLine();
            if(str.isEmpty()) break;
                 for (int i = 0; i < str.length(); i++) {
                      String a=str.substring(i, i+1);
                      if(a.contains("\"")){
                           if(ganjil) {
                                a = a.replaceFirst("\"", "``");
                                ganjil=false;
                           }else{
                                a = a.replaceFirst("\"", "''");
                                ganjil=true;
                           }}
                     System.out.print(a);
             }
             System.out.println("");
     }
}

}
Read More