[英]How can I create a string in C# programmatically?
I have a string, and I want to add a number of spaces to the beginning of that string based on an int variable. 我有一个字符串,我想基于一个int变量在该字符串的开头添加一些空格。
I want to do something like this: 我想做这样的事情:
int NumberOfTabs = 2;
string line = "my line";
string line = String.Format("{0}{1}", " " * NumberOfTabs, line);
...and now line would have 8 spaces ...现在行将有8个空格
What is the easiest way to do this? 最简单的方法是什么?
You can use the String(char, Int32) constructor like this: 您可以使用String(char,Int32)构造函数,如下所示:
string line = String.Format("{0}{1}", new String(' ', NumberofTabs * 4), line);
or a bit more efficient: 或者更有效率:
string line = String.Concat(new String(' ', NumberofTabs * 4), line);
or, a bit more concise :) 或者,更简洁一点:)
string line = new String(' ', NumberofTabs * 4).Concat(line);
A comment made a good point, if you want to actually have the tab character, just change the ' '
to '\\t'
and take out the * 4
like this: 评论提出了一个很好的观点,如果你想要实际拥有制表符,只需将
' '
改为'\\t'
并取出* 4
如下所示:
string line = String.Concat(new String('\t', NumberofTabs), line);
int i=8;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(" ", i);
new string(' ', NumberOfTabs )
str = str.PadLeft(str.Length+tabs*4);
In C# strings are immutable. 在C#中,字符串是不可变的。 You should really use the stringbuilder class.
你应该真的使用stringbuilder类。
Code examples are listed in the link: 代码示例列在链接中:
http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx
你可以使用这样的东西:
String.Empty.PadRight(NumberOfTabs)
You can add tabs at the beginning of your text like this: 您可以在文本的开头添加标签,如下所示:
line.PadLeft(NumberOfTabs, '\t');
\\t being the escape character for "tab" ( Inserting a tab character into text using C# ) \\ t是“标签”的转义字符( 使用C#将标签字符插入文本 )
int NumberOfTabs = 2;
string line = "my line";
string results = line.PadLeft(line.Length + NumberOfTabs, ' ');
不是任何衡量标准的最佳答案,但这是一个有趣的,一个LINQ单线程:
var result = new string(Enumerable.Repeat(' ', count).Concat("my line").ToArray());
You can create a new string containing a custom number of spaces. 您可以创建一个包含自定义空格数的新字符串。 Unfortunately, there's no string multiplication like in Python (
" " * 2
). 不幸的是,Python中没有字符串乘法(
" " * 2
)。 But you can multiply the number of spaces by 4 to get "tabs": 但是你可以将空格数乘以4得到“标签”:
int numberOfTabs = 2;
string line = "my line";
string whitespaces = new string(' ', numberOfTabs * 4);
string s = whitespaces + line;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.