必须有更好的方法来做到这一点.我只想将长字符串分成60个字符行,但不要破坏单词.所以它不必添加多达60个字符,只需要小于60.
下面的代码是我所拥有的并且它有效,但我认为有更好的方法.任何人?
修改为使用StringBuilder并修复了删除重复单词的问题.也不想使用正则表达式,因为我认为这将比我现在的效率低.
public static List<String> FormatMe(String Message)
{
Int32 MAX_WIDTH = 60;
List<String> Line = new List<String>();
String[] Words;
Message = Message.Trim();
Words = Message.Split(" ".ToCharArray());
StringBuilder s = new StringBuilder();
foreach (String Word in Words)
{
s.Append(Word + " ");
if (s.Length > MAX_WIDTH)
{
s.Replace(Word, "", 0, s.Length - Word.Length);
Line.Add(s.ToString().Trim());
s = new StringBuilder(Word + " ");
}
}
if (s.Length > 0)
Line.Add(s.ToString().Trim());
return Line;
}
Run Code Online (Sandbox Code Playgroud)
谢谢
另一个(现在是TESTED)样本,与Keith方法非常相似:
static void Main(string[] args)
{
const Int32 MAX_WIDTH = 60;
int offset = 0;
string text = Regex.Replace(File.ReadAllText("oneline.txt"), @"\s{2,}", " ");
List<string> lines = new List<string>();
while (offset < text.Length)
{
int index = text.LastIndexOf(" ",
Math.Min(text.Length, offset + MAX_WIDTH));
string line = text.Substring(offset,
(index - offset <= 0 ? text.Length : index) - offset );
offset += line.Length + 1;
lines.Add(line);
}
}
Run Code Online (Sandbox Code Playgroud)
我在这个文件上运行它,所有换行符都用""替换.
尝试这个:
const Int32 MAX_WIDTH = 60;
string text = "...";
List<string> lines = new List<string>();
StringBuilder line = new StringBuilder();
foreach(Match word in Regex.Matches(text, @"\S+", RegexOptions.ECMAScript))
{
if (word.Value.Length + line.Length + 1 > MAX_WIDTH)
{
lines.Add(line.ToString());
line.Length = 0;
}
line.Append(String.Format("{0} ", word.Value));
}
if (line.Length > 0)
line.Append(word.Value);
Run Code Online (Sandbox Code Playgroud)
请同时查看:如何使用正则表达式添加换行符?
| 归档时间: |
|
| 查看次数: |
5820 次 |
| 最近记录: |