算法竞赛入门-Tex中的引号(Tex Quotes)

13 篇文章 0 订阅
11 篇文章 2 订阅

1. 题目

今天第二道

在Tex中,做双引号的" `` ",右双引号是"  '' "(两个回车左边的).输入一篇包含双引号的文章,你的任务是把它转换成TeX的格式。

样例输入

"To be or not to be,"quoth the Bard,"that is the question".

样例输出

 ``To be or not to be''quoth the Bard,``that is the question''.

2.思路

 第一反应采用正则表达式进行匹配,然后通过一个计数变量判断当前为左右引号(实现这种);

 第二种:输入一个字符便判断然后进行转换

3.代码

package basic.第三章;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * TeX中的引号 (TexQuotes)
 * Created by Administrator on 2018/4/8.
 * 题目:在Tex中,做双引号的" `` ",右双引号是"  '' "(两个回车左边的).输入一篇包含双引号的文章,你的任务是把它转换成TeX的格式。
 * 样例输入:"To be or not to be,"quoth the Bard,"that is the question".
 * 样例输出:``To be or not to be,''quoth the Bard,``that is the question''.
 * 思路:采用正则进行匹配,找到则进行替换,通过一个计数变量判断当前是左右引号;
 *
 * @author 春风吹又生
 */
public class Project3_5 {
    public static void main(String[] args) {
        Scanner read = new Scanner(System.in);
        String line = read.nextLine();
        //1.将正在表达式封装成对象Patten 类来实现
        Pattern pattern = Pattern.compile("\"");
        //2.将字符串和正则表达式相关联
        Matcher matcher = pattern.matcher(line);
        StringBuilder sb = new StringBuilder(line);
        int i = 0;
        while (matcher.find()) {  //查找符合规则的子串
            if (i % 2 == 0) {    //获取的字符串的首位置和末位置
                sb.replace(matcher.start(), matcher.end(), "`");
            } else {
                sb.replace(matcher.start(), matcher.end(), "'");
            }
            i++;
        }
        line = sb.toString();
        System.out.println(line.replaceAll("`", "``").replaceAll("'", "''"));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值