Java:从字符串中删除注释

编程入门 行业动态 更新时间:2024-10-27 02:23:17
本文介绍了Java:从字符串中删除注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想做一个函数,它获取一个字符串,如果它有内联注释,它删除它。我知道这听起来很简单,但我想确保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:从字符串中删除注释

    本文发布于:2023-11-11 08:07:31,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1577843.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:字符串   注释   Java

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!