Java:从字符串中删除注释 [英] Java: Removing comments from string
问题描述
我想做一个函数,它获取一个字符串,如果它有内联注释,它删除它。我知道这听起来很简单,但我想确保im这样做正确,例如:
I'd like to do a function which gets a string and in case it has inline comments it removes it. I know it sounds pretty simple but i wanna make sure im doing this right, for example:
private String filterString(String code) {
// lets say code = "some code //comment inside"
// return the string "some code" (without the comment)
}
我想了两种方法:随时咨询其他意见
I thought about 2 ways: feel free to advice otherwise
- 迭代字符串并查找双内联括号和使用substring方法。
- regex方法..(im不那么确定bout it)
可以告诉我什么是最好的方法,并告诉我应该怎么做? (请不要建议太先进的解决方案)
can u tell me what's the best way and show me how it should be done? (please don't advice too advanced solutions)
编辑:可以用扫描仪对象做某些事情吗? (im using this object anyway)
edited: can this be done somehow with Scanner object? (im using this object anyway)
推荐答案
要使用正则表达式替换找到常量子字符串之前的子字符串有点多。
To find the substring before a constant substring using a regular expression replacement is a bit much.
您可以使用 indexOf()
来检查注释开始的位置和 substring()
获取第一部分,如:
You can do it using indexOf()
to check for the position of the comment start and substring()
to get the first part, something like:
String code = "some code // comment";
int offset = code.indexOf("//");
if (-1 != offset) {
code = code.substring(0, offset);
}
这篇关于Java:从字符串中删除注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!