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

如何在C#代码中替换\r\n实现字符串换行?

在C#中替换\r\n插入新行的几种方法

针对你提供的Excel验证代码,这里有几种替代\r\n插入新行的实用方式:

1. 使用Environment.NewLine(推荐跨平台场景)

这是C#提供的平台无关换行符,会自动根据运行环境选择Windows的\r\n或类Unix系统的\n,适配性更强。

替换代码示例:

} else if (rowCount <= 2 && wsName.ToLower().Contains("ver82")) { 
    premilinaryValidationErrors.Append($"There are no employees in the census file you are attempting to upload. {Environment.NewLine} Please verify you are uploading the correct template.");
} else if (rowCount <= 1 && wsName.ToLower().Contains("ver81")) { 
    presilinaryValidationErrors.Append($"There are no employees in the census file you are attempting to upload. {Environment.NewLine} Please verify you are uploading the correct template.");
}

也可以用字符串拼接的方式:

premilinaryValidationErrors.Append("There are no employees in the census file you are attempting to upload. " + Environment.NewLine + " Please verify you are uploading the correct template.");

2. 直接使用\n换行符

如果你的应用只运行在类Unix环境,或者前端/接收端只识别\n,可以直接把\r\n替换成\n:

premilinaryValidationErrors.Append("There are no employees in the census file you are attempting to upload. \n Please verify you are uploading the correct template.");

3. 逐字字符串(@前缀)直观换行

用@标记逐字字符串后,你可以直接在代码里换行,字符串会保留这个换行格式,可读性更好:

premilinaryValidationErrors.Append(@"There are no employees in the census file you are attempting to upload. 
 Please verify you are uploading the correct template.");

内容的提问来源于stack exchange,提问作者Hobbs Martin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 18:30:45