C #에서 문자를 반복하는 가장 좋은 방법
\t
C #에서 문자열을 생성하는 가장 좋은 방법은 무엇입니까?
나는 C #을 배우고 같은 것을 말하는 다른 방법으로 실험하고 있습니다.
Tabs(uint t)
함수입니다 리턴 string
와 t
양 \t
의
예를 들어 Tabs(3)
반품"\t\t\t"
다음 세 가지 구현 방법 중 Tabs(uint numTabs)
가장 좋은 것은 무엇입니까?
물론 그것은 "최고"가 무엇을 의미하는지에 달려 있습니다.
LINQ 버전은 두 줄뿐입니다. 그러나 반복 및 집계에 대한 호출이 불필요하게 시간 / 자원을 소비합니까?
StringBuilder
버전은 매우 분명하다하지만입니다StringBuilder
클래스는 어떻게 든 느린?string
버전은 이해하기 쉬운 의미하는 기본이다.전혀 중요하지 않습니까? 모두 동등합니까?
C #에 대해 더 잘 이해하는 데 도움이되는 모든 질문입니다.
private string Tabs(uint numTabs)
{
IEnumerable<string> tabs = Enumerable.Repeat("\t", (int) numTabs);
return (numTabs > 0) ? tabs.Aggregate((sum, next) => sum + next) : "";
}
private string Tabs(uint numTabs)
{
StringBuilder sb = new StringBuilder();
for (uint i = 0; i < numTabs; i++)
sb.Append("\t");
return sb.ToString();
}
private string Tabs(uint numTabs)
{
string output = "";
for (uint i = 0; i < numTabs; i++)
{
output += '\t';
}
return output;
}
이것에 대해 :
string tabs = new String('\t', n);
n
문자열을 반복하려는 횟수는 어디에 있습니까 ?
또는 더 나은 :
static string Tabs(int n)
{
return new String('\t', n);
}
string.Concat(Enumerable.Repeat("ab", 2));
보고
"아밥"
과
string.Concat(Enumerable.Repeat("a", 2));
보고
"aa"
에서...
.net에서 문자열 또는 문자를 반복하는 내장 기능이 있습니까?
모든 버전의 .NET에서 다음과 같이 문자열을 반복 할 수 있습니다.
public static string Repeat(string value, int count)
{
return new StringBuilder(value.Length * count).Insert(0, value, count).ToString();
}
캐릭터를 반복하는 new String('\t', count)
것이 최선의 방법입니다. @CMS의 답변을 참조하십시오 .
가장 좋은 버전은 확실히 내장 방식을 사용하는 것입니다.
string Tabs(int len) { return new string('\t', len); }
다른 솔루션 중에서 가장 쉬운 것을 선호하십시오. 이것이 너무 느리게 증명되는 경우에만보다 효율적인 솔루션을 위해 노력하십시오.
If you use a Nonsense: of course the above code is more efficient.StringBuilder
and know its resulting length in advance, then also use an appropriate constructor, this is much more efficient because it means that only one time-consuming allocation takes place, and no unnecessary copying of data.
Extension methods:
public static string Repeat(this string s, int n)
{
return new String(Enumerable.Range(0, n).SelectMany(x => s).ToArray());
}
public static string Repeat(this char c, int n)
{
return new String(c, n);
}
What about using extension method?
public static class StringExtensions
{
public static string Repeat(this char chatToRepeat, int repeat) {
return new string(chatToRepeat,repeat);
}
public static string Repeat(this string stringToRepeat,int repeat)
{
var builder = new StringBuilder(repeat*stringToRepeat.Length);
for (int i = 0; i < repeat; i++) {
builder.Append(stringToRepeat);
}
return builder.ToString();
}
}
You could then write :
Debug.WriteLine('-'.Repeat(100)); // For Chars
Debug.WriteLine("Hello".Repeat(100)); // For Strings
Note that a performance test of using the stringbuilder version for simple characters instead of strings gives you a major preformance penality : on my computer the difference in mesured performance is 1:20 between: Debug.WriteLine('-'.Repeat(1000000)) //char version and
Debug.WriteLine("-".Repeat(1000000)) //string version
How about this:
//Repeats a character specified number of times
public static string Repeat(char character,int numberOfIterations)
{
return "".PadLeft(numberOfIterations, character);
}
//Call the Repeat method
Console.WriteLine(Repeat('\t',40));
I know that this question is five years old already but there is a simple way to repeat a string that even works in .Net 2.0.
To repeat a string:
string repeated = new String('+', 3).Replace("+", "Hello, ");
Returns
"Hello, Hello, Hello, "
To repeat a string as an array:
// Two line version.
string repeated = new String('+', 3).Replace("+", "Hello,");
string[] repeatedArray = repeated.Split(',');
// One line version.
string[] repeatedArray = new String('+', 3).Replace("+", "Hello,").Split(',');
Returns
{"Hello", "Hello", "Hello", ""}
Keep it simple.
Let's say you want to repeat '\t' n number of times, you can use;
String.Empty.PadRight(n,'\t')
Your first example which uses Enumerable.Repeat
:
private string Tabs(uint numTabs)
{
IEnumerable<string> tabs = Enumerable.Repeat(
"\t", (int) numTabs);
return (numTabs > 0) ?
tabs.Aggregate((sum, next) => sum + next) : "";
}
can be rewritten more compactly with String.Concat
:
private string Tabs(uint numTabs)
{
return String.Concat(Enumerable.Repeat("\t", (int) numTabs));
}
Using String.Concat
and Enumerable.Repeat
which will be less expensive than using String.Join
public static Repeat(this String pattern, int count)
{
return String.Concat(Enumerable.Repeat(pattern, count));
}
var str = new string(Enumerable.Repeat('\t', numTabs).ToArray());
The answer really depends on the complexity you want. For example, I want to outline all my indents with a vertical bar, so my indent string is determined as follows:
return new string(Enumerable.Range(0, indentSize*indent).Select(
n => n%4 == 0 ? '|' : ' ').ToArray());
And yet another method
new System.Text.StringBuilder().Append('\t', 100).ToString()
You can create an extension method
static class MyExtensions
{
internal static string Repeat(this char c, int n)
{
return new string(c, n);
}
}
Then you can use it like this
Console.WriteLine('\t'.Repeat(10));
For me is fine:
public static class Utils
{
public static string LeftZerosFormatter(int zeros, int val)
{
string valstr = val.ToString();
valstr = new string('0', zeros) + valstr;
return valstr.Substring(valstr.Length - zeros, zeros);
}
}
Without a doubt the accepted answer is the best and fastest way to repeat a single character.
Binoj Anthony's answer is a simple and quite efficient way to repeat a string.
However, if you don't mind a little more code, you can use my array fill technique to efficiently create these strings even faster. In my comparison tests, the code below executed in about 35% of the time of the StringBuilder.Insert code.
public static string Repeat(this string value, int count)
{
var values = new char[count * value.Length];
values.Fill(value.ToCharArray());
return new string(values);
}
public static void Fill<T>(this T[] destinationArray, params T[] value)
{
if (destinationArray == null)
{
throw new ArgumentNullException("destinationArray");
}
if (value.Length > destinationArray.Length)
{
throw new ArgumentException("Length of value array must not be more than length of destination");
}
// set the initial array value
Array.Copy(value, destinationArray, value.Length);
int copyLength, nextCopyLength;
for (copyLength = value.Length; (nextCopyLength = copyLength << 1) < destinationArray.Length; copyLength = nextCopyLength)
{
Array.Copy(destinationArray, 0, destinationArray, copyLength, copyLength);
}
Array.Copy(destinationArray, 0, destinationArray, copyLength, destinationArray.Length - copyLength);
}
For more about this array fill technique, see Fastest way to fill an array with a single value
Try this:
- Add Microsoft.VisualBasic reference
- Use: String result = Microsoft.VisualBasic.Strings.StrDup(5,"hi");
- Let me know if it works for you.
Albeit very similar to a previous suggestion, I like to keep it simple and apply the following:
string MyFancyString = "*";
int strLength = 50;
System.Console.WriteLine(MyFancyString.PadRight(strLength, "*");
Standard .Net really,
참고URL : https://stackoverflow.com/questions/411752/best-way-to-repeat-a-character-in-c-sharp
'Nice programing' 카테고리의 다른 글
JavaScript에서 문자열을 Base64로 어떻게 인코딩 할 수 있습니까? (0) | 2020.09.29 |
---|---|
Git에서 단일 브랜치를 어떻게 복제합니까? (0) | 2020.09.29 |
event.stopPropagation과 event.preventDefault의 차이점은 무엇입니까? (0) | 2020.09.29 |
커밋 메시지로 Git 저장소를 검색하는 방법은 무엇입니까? (0) | 2020.09.29 |
git은 커밋되지 않았거나 저장되지 않은 모든 변경 사항을 실행 취소합니다. (0) | 2020.09.29 |