你的问题有点不清楚(例子有助于澄清).此外,你没有完全指定你期望的输出(当第二个字符串不能在第一个字符串中居时我们抛出因为它太长了吗?)你会发现完全指定你的要求将帮助你写你的码!也就是说,我认为你正在寻找类似的东西.
使用
public static string CenterWithRespectTo(string s, string against) {
if(s == null) {
throw new ArgumentNullException("s");
}
if(against == null) {
throw new AgrumentNullException("against");
}
if (s.Length > against.Length) {
throw new InvalidOperationException();
}
int halfSpace = (against.Length - s.Length) / 2;
return s.PadLeft(halfSpace + s.Length).PadRight(against.Length);
}
Run Code Online (Sandbox Code Playgroud)
以便
string s = "Hello";
string against = "My name is Slim Shady";
Console.WriteLine(CenterWithRespectTo(s, against) + "!");
Console.WriteLine(against);
Run Code Online (Sandbox Code Playgroud)
产生
Hello !
My name is Slim Shady
Run Code Online (Sandbox Code Playgroud)
(无关的'!'是这样你可以看到填充.)
您可以轻松地修改它,以便在存在奇数额外空间的情况下,根据您的需要(重构接受参数!),额外空间在左侧或右侧(当前它在右侧).
| 归档时间: |
|
| 查看次数: |
1840 次 |
| 最近记录: |