简体   繁体   English

C#:我希望单词的每个字母都以新行开头

[英]C#: I want every letter of a word to begin in a new line

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 ?它应该是Environment.NewLine东西吗?

Here you go:干得好:

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

foreach (char c in arr)
{
    Console.WriteLine(c);
}

Implementation by Join method:通过Join方法实现:

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

Console.WriteLine(textInLines);

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当然,如果您喜欢 linq,您可以将字符串转换为单字符字符串列表,并通过在每个字符之间添加新行而不是在控制台上打印来合并它

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

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.我知道他们有很多方法可以使某些事情发挥作用。

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 )此正则表达式搜索任何一个字符(.)并将其替换为找到的字符加上\\n ( $1\\n )

(no, please... it is false... you shouldn't use Regular Expressions in C# unless you are really desperate). (不,拜托......这是错误的......除非你真的很绝望,否则你不应该在C#中使用正则表达式)。

string Hello = "Hello C#";

foreach(char i in Hello)
{
 Console.WriteLine(i);
}

A simpler solution.一个更简单的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM