Monday, April 25, 2011

C# doubt in string operations

Consider 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 to split each characters in the string and manipulate them.?

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

But can u suggest some simpler methods.?!

From stackoverflow
  • 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. 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.
    belugabob : Or 2 adjacent values which add up to more than 10.

0 comments:

Post a Comment