2013-07-11 13 views
8

La stringa ha sia PadLeft sia PadRight. Ho bisogno di un riempimento sia a destra che a sinistra (giustificazione centrale). Esiste un modo standardizzato per farlo, o, meglio ancora, un modo costruito per raggiungere lo stesso obiettivo?Stringa sinistra pad e pad destra (pad centrale)

+6

'Yourstring.PadLeft(). PadRight()'? –

risposta

11

Non che io sappia. Puoi creare un metodo di estensione se vedi di usarlo molto. Supponendo che si desidera la stringa per finire nel centro, usa qualcosa come il seguente

public string PadBoth(string source, int length) 
{ 
    int spaces = length - source.Length; 
    int padLeft = spaces/2 + source.Length; 
    return source.PadLeft(padLeft).PadRight(length); 

} 

Per rendere questo metodo di un'estensione, farlo in questo modo:

namespace System 
{ 
    public static class StringExtensions 
    { 
     public static string PadBoth(this string str, int length) 
     { 
      int spaces = length - str.Length; 
      int padLeft = spaces/2 + str.Length; 
      return str.PadLeft(padLeft).PadRight(length); 
     } 
    } 
} 

Per inciso, ho appena includo le mie estensioni nel namespace di sistema: tocca a te quello che fai.

+0

Modificato l'ultima riga per utilizzare spazi non-breaking (alt + 0160), '.PadRight (lunghezza, '');' . Ciò aiuta a mantenere la visualizzazione del padding anche se l'ambiente di visualizzazione non gradisce più spazi. – ShawnFeatherly

-1

è anche possibile creare il proprio interno in questo modo:

public static string PadBoth(this string s, int padValue) 
{ 
    return s.PadLeft(padValue).PadRight(padValue); 
} 

e utilizzare il metodo PadBoth su stringa.

+2

Prova a eseguire questo, ho la sensazione che farà la stessa cosa di pad lasciato da solo ... –

1

che si possa fare da soli con questo:

string test = "Wibble"; 
    int padTo = 12; 
    int padSize = (padTo - test.Length)/2; 
    if (padSize > 0) { 
     test = test.Trim().PadLeft(test.Length + padSize).PadRight(test.Length + 2 * padSize); 
    } 

Basta regolare questo a che fare con le lunghezze imbottitura dispari come richiesto e renderlo un metodo di estensione se questo rende la vita più facile.

3

Ecco un'implementazione personalizzata, che non richiede la ricostruzione di stringhe.

Inoltre funziona correttamente con i numeri dispari

static string PadCenter(string text, int newWidth) 
    { 
     const char filler = ' '; 
     int length = text.Length; 
     int charactersToPad = newWidth - length; 
     if (charactersToPad < 0) throw new ArgumentException("New width must be greater than string length.", "newWidth"); 
     int padLeft = charactersToPad/2 + charactersToPad%2; 
     //add a space to the left if the string is an odd number 
     int padRight = charactersToPad/2; 

     StringBuilder resultBuilder = new StringBuilder(newWidth); 
     for (int i = 0; i < padLeft; i++) resultBuilder.Insert(i, filler); 
     for (int i = 0; i < length; i++) resultBuilder.Insert(i + padLeft, text[i]); 
     for (int i = newWidth - padRight; i < newWidth; i++) resultBuilder.Insert(i, filler); 
     return resultBuilder.ToString(); 
    } 
0

Ecco una versione leggermente migliorata del metodo di @ David-Colwell extension che prende anche opzionalmente un carattere di riempimento:

namespace System 
{ 
    public static class StringExtensions 
    { 
     public static string PadSides(this string str, int totalWidth, char paddingChar = ' ') 
     { 
      int padding = totalWidth - str.Length; 
      int padLeft = padding/2 + str.Length; 
      return str.PadLeft(padLeft, paddingChar).PadRight(totalWidth, paddingChar); 
     } 
    } 
} 
-1
/* Output looks like this 
     *****Luke***** 
     *****Leia***** 
     *****Han****** 
     **Chewbecca*** */ 

    string result = ""; 
    string names = "Luke,Leia,Han,Chewbecca"; 
    string[] charA = names.Split(','); 

     for (int i = 0; i < charA.Length; i++) 
     { 
      int padLeft = (14 - charA[i].Length)/2; 
      string temp = charA[i].PadLeft(charA[i].Length + padLeft, '*'); 
      result += temp.PadRight(14, '*') + "\n"; 
     } 
     Console.WriteLine(result); 
+1

La forza non è così forte in questo ;-) – Blaatz0r

0

Qui un un po 'di miglioramento, penso.

namespace System 
{ 
    public static class StringExtensions 
    { 
     public static string PadCenter(this string str, int totalLength, char padChar = '\u00A0') 
     { 
      int padAmount = totalLength - str.Length; 

      if (padAmount <= 1) 
      { 
       if (padAmount == 1) 
       { 
        return str.PadRight(totalLength); 
       } 
       return str; 
      } 

      int padLeft = padAmount/2 + str.Length; 

      return str.PadLeft(padLeft).PadRight(totalLength); 
     } 
    } 
} 
Problemi correlati