简体   繁体   中英

String operations in C#

Suppose I have a string "011100011" . Now I need to find another string by adding the adjacent digits of this string, like the output string should be "123210122" .

How do I split each characters in the string and manipulate them?

The method that I thought was to convert the string to integer using Parsing and splitting each character using modulus or something and performing operations on them.

But can you suggest some simpler methods?

Try converting the string to a character array and then subtract '0' from the char values to retrieve an integer value.

string input = "011100011";
int current;

for (int i = 0; i < input.Length; i ++)
{
  current = int.Parse(input[i]);

  // do something with current...
}

Here's a solution which uses some LINQ plus dahlbyk's idea:

string input = "011100011";

// add a 0 at the start and end to make the loop simpler
input = "0" + input + "0"; 

var integers = (from c in input.ToCharArray() select (int)(c-'0'));
string output = "";
for (int i = 0; i < input.Length-2; i++)
{
    output += integers.Skip(i).Take(3).Sum();
}

// output is now "123210122"

Please note:

  • the code is not optimized. Eg you might want to use a StringBuilder in the for loop.
  • What should happen if you have a '9' in the input string -> this might result in two digits in the output string.

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