Reputation: 9966
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
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:
Upvotes: 1
Reputation: 29939
string input = "011100011";
int current;
for (int i = 0; i < input.Length; i ++)
{
current = int.Parse(input[i]);
// do something with current...
}
Upvotes: 1
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