0

So basically I have an input string and I have to return a string after adding space after every character in the string.

Eg. input = abcd output=a b c d

I wrote this piece of code:

class Program
{
    static void Main()
    {
        string input1 = "abcd";
        char[] output = new char[999];
        int j = 0;
    
        for (int i = 0; i < input1.Length; i++)
        {
            output[j] = input1[i];
            j = j + 1;
            output[j] =' ';
        }
    
        Console.Write(output[1]); //Why does this print b? I have inserted a blank space at index 1, right?
    
        for (int i = 0; i < output.Length; i++)
            Console.Write(output[i]);
    
        string op = new string(output);
        return op;
    }
}

So that's my question, how does it get b at index 1 when I have inserted a blank space.
I am not sure if there are any other shortcuts to do this task. I am completely new to C#. Thanks for all the help. :)

EDIT: This is my first time posting here, sorry for the messed up formatting of the text and code.

0

1 Answer 1

4

wouldn't simpler if you use to char array, you get the same results

var input = "abcd";
var output = string.Join(" ", input.ToCharArray());
Sign up to request clarification or add additional context in comments.

2 Comments

This is the best way to do this. @Avishek Paul If you want to know why your code didn't work it is because you're resetting the "space" at the beginning of the next loop. If you step through your debugger you will probably see your output is only one element longer than your input. If you want YOUR code to work then you'll need to increment "j" once more at the end of each loop.
Thank you @dogyear for the explanation. I should have been more careful. :)

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.