You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 05:45:05