2015-12-13 39 views
-1

我想替换运算符之间的字符串。鉴于and,ornot分别代表^v~。下面的代码仅用^替代所有and如何用变量替换段落中的句子

import java.util.Scanner; 

public class Paragraphconv 
{ 

    public static void main(String[] args) { 

     System.out.println("Enter a paragraph "); 

     Scanner scanF = new Scanner(System.in); 

     String str = scanF.nextLine(); 
     String newStr = str.replace("and", "^"); 

     System.out.println(newStr); 

    } 
} 

我已经使用replace()方法试过,我只能更换运营商的符号,同时保持句子在它的地方。


应该发生的是:

INPUT

狗是饿了,人给它食物。本和托比和玛丽亚是 伟大的朋友。你想喝咖啡还是甜的?我不再喜欢你了。

输出

x^y 
x^y^z 
x v y 
~x 

我没有试图改变句子的变量还因为我不知道我应该包括。 (请注意,上面给出的字符串是废话,并由用户输入,即不固定)

+0

向我们显示您的代码。如果你不显示你在做什么,我们怎么可能知道你做错了什么? –

+1

请参阅帮助中心的[我如何提出一个好问题?](http://stackoverflow.com/help/how-to-ask) – SnareChops

+0

我没有替换句子中的代码。因为我不知道如何去做。我只有'String str = yourString.replace(“和”,“^”);'等等来将运算符更改为它的符号:-( – ryannjeffers

回答

0

直接replace不会这样做,正如在帖子的评论中提到的。更好的方法是使用regular expressions来分割每个句子。

  1. 斯普利特段成句子:在Java中,它使用的是PatternMatcher

    我会在2个阶段执行这样的任务来完成。这样做的一个简单的方法是,例如,分裂用分隔字符串“”:

    /* note that split accepts a regex as parameter, so we need to escape '.'' */ 
    String[] sentences = paragraph.split("\\."); 
    for(String sentence : sentences) 
        System.out.println(handleSentence(sentence)); 
    
  2. 现在,主要部分,分析每个句子用正则表达式并处理递归语句的各部分:

    import java.util.regex.Pattern; 
    /* ... */ 
    
    String handleSentence(String s) { 
        Pattern andPattern = Pattern.compile("(.*) and (.*)"); 
        Pattern notPattern = Pattern.compile("not (.*)"); 
        /* patterns for the rest of the operators here... */ 
        Matcher m; 
        m = andPattern.matcher(s); 
        if (m.matches()){ 
         /* we have an "and" sentence */ 
         String preAnd = m.group(1); 
         String postAnd = m.group(2); 
         String res = "(" + handleSentence(preAnd) + "^" + handleSentence(postAnd) + ")"; 
         return res; 
        } 
        m = notPattern.matcher(s); 
        if (m.matches()){ 
         /* we have a "not" sentent */ 
         String postNot = m.group(1); 
         String res = "~" + handleSentence(postNot); 
         return res; 
        } 
    
        /* and so on ... */ 
    
        /* 
        if there's no match, just convert it to xyz etc. 
        nextAvailableVar will check what is the next variable name that is not used 
        and return it as a String 
        */ 
    
        return nextAvailableVar(); 
    } 
    

现在,这个代码是不完整的,当然也有可能是更有效的方式来做到这一点,但它应该给你的如何执行这样的任务的想法。

+0

我很明白你的想法。但是我可以看到输出吗?或至少是建议的产出? – ryannjeffers

+0

这不是一个完整的代码,并没有从书面申请中获取。这只是我所做的一个例子,所以我没有一个可以运行并输出任何东西的可用工作应用程序。我今天晚些时候可能会编写一个这样的例子,但它将不得不等待。如果你明白了,我相信你可以围绕它构建一个简单的应用程序并对其进行测试。 – MByD