unity c# 字符串根据每行字数 追加换行符

unity c# 字符串根据每行字数 追加换行符

在Unity C#中,如果你想要根据每行的字数在字符串中追加换行符,你可以使用以下方法:

 
 
 
 

using System.Text;

public static string InsertNewLineCharacters(string input, int charPerLine)

{

if (input == null || charPerLine <= 0)

{

return input;

}

StringBuilder sb = new StringBuilder();

int length = input.Length;

int currentLineLength = 0;

for (int i = 0; i < length; i++)

{

if (input[i] == '\n')

{

currentLineLength = 0;

}

else

{

currentLineLength++;

if (currentLineLength % charPerLine == 0 && i < length - 1)

{

sb.Append(input[i]).Append('\n');

}

else

{

sb.Append(input[i]);

}

}

}

return sb.ToString();

}

使用这个方法,你可以指定每行的字符数,然后它会在每达到指定的字符数后在字符串中追加一个换行符。例如:

 
 
 
 

string originalString = "这是一个很长的字符串,我们希望在每行达到10个字符后自动插入换行符。";

string stringWithNewLines = InsertNewLineCharacters(originalString, 10);

Debug.Log(stringWithNewLines);

这段代码会在每10个字符后插入一个换行符。

猜你喜欢

转载自blog.csdn.net/qq_21743659/article/details/142105030