Uva 272 Tex Quotes
一、问题描述
在Tex中,左引号是``,右引号是' '。
给定一段包含双引号的段落,你的任务是把它转换成Tex的格式。
二、输入格式
输入是一段包含双引号的段落。
三、输出格式
输入段落的Tex格式。
四、样例输入
"To be or not to be," quoth the Bard, "that
is the question".
The programming contestant replied: "I must disagree.
To `C' or not to `C', that is The Question!"
五、样例输出
``To be or not to be,'' quoth the Bard, ``that
is the question''.
The programming contestant replied: ``I must disagree.
To `C' or not to `C', that is The Question!''
六、思路
题目的关键在于判断一个引号是左引号还是右引号。
为此,引入变量flag,在遍历字符串时,用来记录当前引号的出现次序。
若flag为奇数,引号为左引号;若flag为偶数,引号为右引号。
笔者没有选择直接更改原字符串,而是选择StringBuilder重构字符串,详细见代码部分。
七、代码
import java.util.*;
import java.lang.Math.*;
public class Main {
static int flag = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//一直读取输入
while(scan.hasNextLine()) {
//读取当前输入字符串
String s = scan.nextLine();
StringBuffer sb = new StringBuffer();
//遍历当前输入的字符串
for(int i=0; i<s.length(); i++) {
//如果当前字符为"
if(s.charAt(i)=='\"') {
//更新当前"的出现次序
flag++;
//若当前字符为左引号
if(flag%2==1) {
sb.append("``");
}
//若当前字符为右引号
else {
sb.append("\'\'");
}
}
//如果当前字符不是引号
else {
sb.append(s.charAt(i));
}
}
//输出修改后的字符串
System.out.println(sb.toString());
}
}
}
八、总结
1.转义字符的表示
2.StringBuilder的使用