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

如何处理含单条逗号与换行分隔长字符串的List<string>并输出指定格式

解决方案

你可以直接对不可修改的原有逻辑生成的namesList做如下处理:

  1. 取出namesList中存储的唯一长字符串
  2. 用换行符\n分割字符串得到独立的姓名条目,同时自动过滤掉末尾多余的空行
  3. 遍历每个条目,将条目中的逗号替换为空格,拼接从1开始的序号后输出

可直接运行的代码示例

// 提取集合内的长文本
string rawNameString = namesList[0];
// 按换行分割,自动排除末尾多余的空条目
string[] separateNames = rawNameString.Split('\n', StringSplitOptions.RemoveEmptyEntries);

// 遍历输出目标格式内容
for (int index = 0; index < separateNames.Length; index++)
{
    string formattedName = separateNames[index].Replace(',', ' ');
    Console.WriteLine($"{index + 1}. {formattedName}");
}

兼容低版本运行环境的写法

如果你的运行环境不支持StringSplitOptions枚举,也可以手动判断过滤空值:

string[] separateNames = rawNameString.Split('\n');
for (int index = 0; index < separateNames.Length; index++)
{
    if(string.IsNullOrWhiteSpace(separateNames[index])) continue;
    string formattedName = separateNames[index].Replace(',', ' ');
    Console.WriteLine($"{index + 1}. {formattedName}");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:45:03