0

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?

8
  • I don't understand your example: 011100011 + 011100011 = 22200022. And your example answer has a 3 in it. By adding adjacent digits, I can only get a maximum of 2 in any position. Please clarify your example, then I will try to answer. Commented Mar 19, 2009 at 7:19
  • res[0] = 0+1; res[1] = 0+1+1; res[2] = 1+1+1; res[3] = 1+1+0; etc Commented Mar 19, 2009 at 7:35
  • @Dahlbyk - your explanation doesn't clarify the original question for me, I'm afraid. What does adjeacnet digits mean - 2 adjacent digits, or 3? - best result that I can come up with is 12210012 - the result will always be one character shorter than the input. Commented Mar 19, 2009 at 8:04
  • @belugabob: here's how I understood it: every digit in the output string should be the sum of that digit and its two adjacent digits (in the input string). Commented Mar 19, 2009 at 8:07
  • @Pragadheesh - I think a little more explanation about the problem domain is due - I suspect that a different data type may be an answer to the problem. Commented Mar 19, 2009 at 8:07

3 Answers 3

1

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.
Sign up to request clarification or add additional context in comments.

1 Comment

Or 2 adjacent values which add up to more than 10.
1

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

Comments

1
string input = "011100011";
int current;

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

  // do something with current...
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.