简体   繁体   中英

How get odd chars from String in C#

I am new to C#. My problem is to take odd chars from a string and get a new string from those odds.

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 ):

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 sb = new StringBuilder(name.Length / 2 + 1);

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

string result = sb.ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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