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

能否用String.Join仅拼接每个字符串的指定单个字符?(无循环实现)

解决方案

要实现仅拼接每个字符串中指定位置的字符(以第三个字符为例,对应C#字符串的0索引位置2),且避免显式循环,可以借助LINQ的Select方法做投影处理,再用string.Join完成拼接:

List<string> names = new List<string>() { "John", "Anna", "Monica" };
int targetCharIndex = 2; // 对应第三个字符
var result = string.Join("", names.Select(name => name[targetCharIndex]));
// 输出结果:"hnn"

补充说明

如果需要处理列表中存在长度不足的字符串(避免索引越界),可以在投影时增加判断逻辑:

var result = string.Join("", names.Select(name => 
    name.Length > targetCharIndex ? name[targetCharIndex] : '\0' // 用默认字符替代,也可换成其他占位符
));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 10:15:33