我正在寻找一个将文本居中对齐的 C# 函数或例程。
例如,如果我有一个句子,我注意到当句子对齐到屏幕边缘时,空格被放置在行中。插入的空间从中心开始,并根据需要从两侧移出。
是否有一个 C# 函数可以传递我的字符串,比如 50 个字符,然后返回一个漂亮的 56 个字符的字符串?
提前致谢
罗布
最佳答案
不错的任务。这是一个基于 Linq 扩展方法的解决方案。如果您不想使用它们,请查看以前版本代码的历史记录。在此示例中,中心左侧和右侧的空间在插入顺序方面“相等”。
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static String Justify(String s, Int32 count)
{
if (count <= 0)
return s;
Int32 middle = s.Length / 2;
IDictionary<Int32, Int32> spaceOffsetsToParts = new Dictionary<Int32, Int32>();
String[] parts = s.Split(' ');
for (Int32 partIndex = 0, offset = 0; partIndex < parts.Length; partIndex++)
{
spaceOffsetsToParts.Add(offset, partIndex);
offset += parts[partIndex].Length + 1; // +1 to count space that was removed by Split
}
foreach (var pair in spaceOffsetsToParts.OrderBy(entry => Math.Abs(middle - entry.Key)))
{
count--;
if (count < 0)
break;
parts[pair.Value] += ' ';
}
return String.Join(" ", parts);
}
static void Main(String[] args) {
String s = "skvb sdkvkd s kc wdkck sdkd sdkje sksdjs skd";
String j = Justify(s, 5);
Console.WriteLine("Initial: " + s);
Console.WriteLine("Result: " + j);
Console.ReadKey();
}
}
关于c# - 文本对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1879169/