Uva 272 Tex Quotes

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的使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值