0
        string text = "hello";

        char[] ch = text.ToCharArray();
        
        for (var x=0; x<text.Length; x++)
        {
            Console.Write(ch[x]++); 
        }

This is my current code which produces "hello" as output.

Expecting output to be "ifmmp" as every character is incremented by 1.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Se7en_
  • 3
  • 3
  • 1
    You just need to create a new string from the char array after the loop like `var result = new string(ch);` or alternatively do `Console.Write(++ch[x]);` so you'll increment the char before printing it. – juharr Jan 15 '21 at 02:43
  • @juharr Please answer in the answer section – Asteroids With Wings Jan 15 '21 at 02:46
  • 1
    What do you expect a `z` to become? A `{`? – Charlieface Jan 15 '21 at 02:52
  • 1
    Related question (with regards to incrementing values): [What is the difference between i++ and ++i?](https://stackoverflow.com/questions/3346450/what-is-the-difference-between-i-and-i) – ProgrammingLlama Jan 15 '21 at 02:59
  • Does this answer your question? [What is the difference between i++ and ++i?](https://stackoverflow.com/questions/3346450/what-is-the-difference-between-i-and-i) – Klaus Gütter Jan 15 '21 at 05:47

2 Answers2

1

You're writing and incrementing at the same time, try first incrementing, then writing

for (x=0; x<text.Length; x++){
            ch[x]++;
            Console.Write(ch[x]);
        }
MatthewProSkils
  • 364
  • 2
  • 13
  • Why not `Console.Write(++ch[x])`? – ProgrammingLlama Jan 15 '21 at 02:58
  • @John relying on side effects of `++` is generally risky - any change to the code can change the behavior. It is far easier to reason about the code when one does not do so. I.e. GO simply does not return values from increment to avoid that whole confusion - https://golang.org/doc/faq#inc_dec – Alexei Levenkov Jan 15 '21 at 03:45
  • @AlexeiLevenkov I thought that `++x` vs `x++` was defined behaviour in C-style languages? I agree that it's easier to follow the code when things are more explicitly written though. – ProgrammingLlama Jan 15 '21 at 03:46
  • 1
    @John it is mostly defined... like `++x++ - ++x++` I believe allowed to be -1,0,1 based on phase of the moon in C/C++... Or change from OP's code to one shown in this post - just inlinining that x++ to the Write - pretty innocent and easy to overlook. There is also need to make sure it was not misplaced `]` during code review - `ch[x]++` vs. `ch[x++]` ... just not really worth learning all defined and more importantly undefined behaviors associated with return values. – Alexei Levenkov Jan 15 '21 at 04:01
0

Or if you have LINQ OCD

Console.WriteLine(string.Concat(text.Select(x => ++x)));
TheGeneral
  • 79,002
  • 9
  • 103
  • 141