6
using System;

class HelloCSharp
{
     static void Main()
     {
         Console.WriteLine("Hello C#");
     }
}

I want the output to be:

H
e
l
l
o 

C
#

but every letter should start on a new line

I am new I know but I keep searching and can't find the answer. Should it be something with Environment.NewLine ?

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
test player
  • 333
  • 4
  • 14

5 Answers5

11

Here you go:

string str = "Hello C#"
char[] arr = str.ToCharArray();

foreach (char c in arr)
{
    Console.WriteLine(c);
}
Behzad
  • 3,502
  • 4
  • 36
  • 63
Luthando Ntsekwa
  • 4,192
  • 6
  • 23
  • 52
6

Implementation by Join method:

var text = "Hello C#".ToCharArray();
var textInLines = string.Join("\n", text);

Console.WriteLine(textInLines);
Behzad
  • 3,502
  • 4
  • 36
  • 63
5

Write a function to loop through a string. Like so:

void loopThroughString(string loopString)
{
    foreach (char c in loopString)
    {
        Console.WriteLine(c);
    }
}

now you can call this function:

loopThroughString("Hello c#");

EDIT

Of, if you like linq you can turn the string into a List of one-character strings and merge it by adding new lines to between each character and than printing that on the console

string myString = "Hello c#";
List<string> characterList = myString.Select(c => c.ToString()).ToList();
Console.WriteLine(string.Join("\n", characterList));
Jonidas
  • 187
  • 4
  • 21
1

Thank you all but all options that you have given looks a bit complicated. Is not this easier:

const string world = "Hello World!";
 for ( int i = 0; i < world.Length; i++)
    {
        Console.WriteLine(world[i]);
    }

I am just asking because I have just started learning and is not the most effective and fastest way to write a program the best? I know that they are many ways to make something work.

test player
  • 333
  • 4
  • 14
0

Real men only use Regular expressions, for everything! :-)

string str = "Hello\nC#";
string str2 = Regex.Replace(str, "(.)", "$1\n", RegexOptions.Singleline);
Console.Write(str2);

This regular expression search for any one character (.) and replace it with the found character plus a \n ($1\n)

(no, please... it is false... you shouldn't use Regular Expressions in C# unless you are really desperate).

xanatos
  • 109,618
  • 12
  • 197
  • 280