如何删除没有正则表达式的注释

时间:2015-02-05 02:35:29

标签: java

所以,我的任务是从输入的字符串中删除所有/ * insert_comment * /。我想出了如何使用一个块注释来完成它,但我必须在一个字符串中使用多个块注释。

我知道如何做到这一点,但我不知道如何在我的代码中实现它。我尝试过搜索,但大多数解决方案都涉及正则表达式,我不允许使用。

和顺便说一句,该代码段无法运行



public static String removeComments(String s)
int index = 0;
String new = "";


while (index <= s.length())
{
if( s.charAt(index) = (I don't know how to do this) "/*"
String temp = s.substring(0, index)
index++;
[somehow makes it loop until it reaches */]
new = new.concat(temp)

else
index++

  return new;
&#13;
&#13;
&#13;

是的,这没有多大意义,但我很困惑。我现在也病了,不能直接思考,但我想完成这项工作,所以我不会比现在更落后。非常感谢你们!

2 个答案:

答案 0 :(得分:0)

我知道会有更多的解决方案,但这个解决方案肯定会有效:

public static void main(String[] args) {

        String stringWithComments = "mystring   /*this is a comment*/";

        String comment = stringWithComments.substring(stringWithComments.indexOf("/*") + 2 , stringWithComments.indexOf("*/")); // +2 because the String will start from "/*"
        System.out.println(comment);    // this prints out the extracted comment

        System.out.println(stringWithComments.replace("/*" + comment + "*/" , "")); //replaces your /*comment*/ with an empty string

    }

修改

输出:

this is a comment
mystring

希望它有所帮助。

答案 1 :(得分:0)

public class StringRemover {

    public String remove(String originalText){

        String text = originalText, comment = "";
        int index = 0;
        while( index != -1){

            comment = text.substring(text.indexOf("/*"),text.indexOf("*/")+2);
            //System.out.println("comment :"+comment);
            text = text.replace(comment, "");

            index = text.indexOf("/*");
        }
        return text;
    }
}
class RunTest
{
    public static void main(String cp[]){

        String sampleText = "This is Line1\n /* Comment1 */ \nThis is Line2 \n /* Comment2 */ " +
                "\nThis is Line3 \n /* Comment3 */ \nEnd";
        StringRemover sr = new StringRemover();
        String result = sr.remove(sampleText);
        System.out.println("Before Removing comments :\n"+sampleText);
        System.out.println("\nAfter Removing comments :\n"+result);
    }
}

输出:

Before Removing comments :
This is Line1
 /* Comment1 */ 
This is Line2 
 /* Comment2 */ 
This is Line3 
 /* Comment3 */ 
End

After Removing comments :
This is a Line1

This is Line2 

This is Line3 

End