简体   繁体   English

如何从C#中的String获取奇数字符

[英]How get odd chars from String in C#

I am new to C#. 我是C#的新手。 My problem is to take odd chars from a string and get a new string from those odds. 我的问题是从string获取奇数字符 ,并从这些概率中获得新的string

string name = "Filip"; // expected output ="Flp"

I don't want to take, for example, 例如,我不想

string result = name.Substring(0, 1) + name.Substring(2, 1) + ... etc.

I need a function for this operation. 我需要执行此操作的功能。

Try Linq (you actually want even characters since string is zero-based ): 尝试使用Linq (由于string 基于零,所以实际上您甚至需要字符):

string name = "Filip";
string result = string.Concat(name.Where((c, i) => i % 2 == 0));

In case of good old loop implementation, I suggest building the string with a help of StringBuilder : 如果有良好的旧循环实现,我建议借助StringBuilder 构建 string

StringBuilder sb = new StringBuilder(name.Length / 2 + 1);

for (int i = 0; i < name.Length; i += 2)
  sb.Append(name[i]);

string result = sb.ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM