C#: I want every letter of a word to begin in a new line
Asked Answered
L

5

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 ?

Lsd answered 28/7, 2015 at 9:40 Comment(1)
loop through the characters in the string and use Environment.NewLine as you guessed.Freightage
D
11

Here you go:

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

foreach (char c in arr)
{
    Console.WriteLine(c);
}
Darg answered 28/7, 2015 at 9:46 Comment(1)
Well, that works with those in the BMP at least. Hope you don't get anything outside, nor multi-codepoint ones.Aeronautics
B
6

Implementation by Join method:

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

Console.WriteLine(textInLines);
Borgerhout answered 28/7, 2015 at 9:58 Comment(0)
T
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));
Titration answered 28/7, 2015 at 9:49 Comment(0)
L
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.

Lsd answered 28/7, 2015 at 10:9 Comment(0)
V
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).

Volin answered 28/7, 2015 at 10:11 Comment(1)
as the old joke goes - you used a regex to solve a problem. now you have 2 problems.Freightage

© 2022 - 2024 — McMap. All rights reserved.