将String对中另一个字符串

Kob*_*kie -1 c#

我希望通过确保显示的第二个字符串显示在第一个字符串输出的中心,将字符串居中于另一个字符串.我如何在C#中这样做呢.提前致谢

jas*_*son 5

你的问题有点不清楚(例子有助于澄清).此外,你没有完全指定你期望的输出(当第二个字符串不能在第一个字符串中居时我们抛出因为它太长了吗?)你会发现完全指定你的要求将帮助你写你的码!也就是说,我认为你正在寻找类似的东西.

使用

 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)

(无关的'!'是这样你可以看到填充.)

您可以轻松地修改它,以便在存在奇数额外空间的情况下,根据您的需要(重构接受参数!),额外空间在左侧或右侧(当前它在右侧).