SyncMaster
SyncMaster

Reputation: 9966

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?

Upvotes: 0

Views: 768

Answers (3)

M4N
M4N

Reputation: 96626

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. E.g. 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.

Upvotes: 1

string input = "011100011";
int current;

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

  // do something with current...
}

Upvotes: 1

dahlbyk
dahlbyk

Reputation: 77620

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

Upvotes: 1

Related Questions