C#如何移除字符串中/*与*/包裹的注释片段
问题原因
String.Remove(int startIndex, int count)方法的第二个参数是要删除的字符总长度,不是注释结束位置的索引值,你原有逻辑的长度计算错误,导致裁剪结果不符合预期。
最快实现方案(单段注释场景)
该方案仅做两次索引查找+一次字符串裁剪,无额外开销,性能最优:
string input = "Hello /*test*/World!"; string output = input; // 查找注释起始标记位置 int startCommentIndex = input.IndexOf("/*"); // 从注释起始位置向后查找结束标记,避免匹配到无关的*/ int endCommentIndex = input.IndexOf("*/", startCommentIndex); if (startCommentIndex >= 0 && endCommentIndex >= 0) { // 计算需删除的总长度:结束标记位置 - 起始位置 + 结束标记自身的2位字符长度 int removeLength = endCommentIndex - startCommentIndex + 2; output = input.Remove(startCommentIndex, removeLength); }
多段注释批量删除方案
如果存在多段/*...*/格式的注释需要统一删除,可使用正则实现,代码更简洁:
using System.Text.RegularExpressions; string input = "Hello /*test*/World! /*第二处注释*/测试内容"; string output = Regex.Replace(input, @"/\*.*?\*/", string.Empty);
内容的提问来源于stack exchange,提问作者AZ Software
相关产品推荐
相关产品推荐

