Jak mogę wstawić napis w Javie?

Czy Jest jakiś łatwy sposób na wstawianie łańcuchów w Javie?

Wygląda na coś, co powinno być w jakimś Stringutilowym API, ale nie mogę znaleźć niczego, co by to robiło.

Author: Jason Plank, 2008-12-23

26 answers

Apache StringUtils ma kilka metod: leftPad, rightPad, center oraz repeat.

Ale proszę pamiętać, że-jak inni wspominali i wykazywali w tej odpowiedzi - String.format() A Klasy Formatter w JDK są lepszymi opcjami. Użyj ich w kodzie commons.

 149
Author: GaryF,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-23 22:09:29

Od Javy 1.5, String.format() może być użyty do lewego/prawego padu danego ciągu.

public static String padRight(String s, int n) {
     return String.format("%1$-" + n + "s", s);  
}

public static String padLeft(String s, int n) {
    return String.format("%1$" + n + "s", s);  
}

...

public static void main(String args[]) throws Exception {
 System.out.println(padRight("Howto", 20) + "*");
 System.out.println(padLeft("Howto", 20) + "*");
}
/*
  output :
     Howto               *
                    Howto*
*/
 549
Author: RealHowTo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-11 20:09:01

Padding do 10 znaków:

String.format("%10s", "foo").replace(' ', '*');
String.format("%-10s", "bar").replace(' ', '*');
String.format("%10s", "longer than 10 chars").replace(' ', '*');

Wyjście:

  *******foo
  bar*******
  longer*than*10*chars

Wyświetl " * " dla znaków hasła:

String password = "secret123";
String padded = String.format("%"+password.length()+"s", "").replace(' ', '*');

Wyjście ma taką samą długość jak ciąg hasła:

  secret123
  *********
 230
Author: leo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-31 09:13:08

W guawa , to jest proste:

Strings.padStart("string", 10, ' ');
Strings.padEnd("string", 10, ' ');
 84
Author: Garrett Hall,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-21 15:56:44

Coś prostego:

Wartość powinna być łańcuchem znaków. przekonwertuj go na string, jeśli nie jest. Jak "" + 123 lub Integer.toString(123)

// let's assume value holds the String we want to pad
String value = "123";

Podłańcuch zaczyna się od indeksu wartości length char do długości końca wyściełanego:

String padded="00000000".substring(value.length()) + value;

// now padded is "00000123"

Dokładniej

Pad prawy:

String padded = value + ("ABCDEFGH".substring(value.length())); 

// now padded is "123DEFGH"

Pad lewy:

String padString = "ABCDEFGH";
String padded = (padString.substring(0, padString.length() - value.length())) + value;

// now padded is "ABCDE123"
 29
Author: Shimon Doodkin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-02 13:44:06

Spójrz na org.apache.commons.lang.StringUtils#rightPad(String str, int size, char padChar).

Ale algorytm jest bardzo prosty (pad aż do znaków rozmiaru):

public String pad(String str, int size, char padChar)
{
  StringBuffer padded = new StringBuffer(str);
  while (padded.length() < size)
  {
    padded.append(padChar);
  }
  return padded.toString();
}
 22
Author: Arne Burmeister,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-12-23 09:24:38

Oprócz Apache Commons, Zobacz także String.format, które powinny być w stanie zająć się prostym wypełnieniem (np. spacjami).

 21
Author: Miserable Variable,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-12-23 09:24:20
public static String LPad(String str, Integer length, char car) {
  return str
         + 
         String.format("%" + (length - str.length()) + "s", "")
                     .replace(" ", String.valueOf(car));
}

public static String RPad(String str, Integer length, char car) {
  return String.format("%" + (length - str.length()) + "s", "")
               .replace(" ", String.valueOf(car)) 
         +
         str;
}

LPad("Hi", 10, 'R') //gives "RRRRRRRRHi"
RPad("Hi", 10, 'R') //gives "HiRRRRRRRR"
RPad("Hi", 10, ' ') //gives "Hi        "
//etc...
 14
Author: Eduardo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-10 07:48:54

Trochę mi to zajęło. Prawdziwym kluczem jest odczytanie dokumentacji Formatera.

// Get your data from wherever.
final byte[] data = getData();
// Get the digest engine.
final MessageDigest md5= MessageDigest.getInstance("MD5");
// Send your data through it.
md5.update(data);
// Parse the data as a positive BigInteger.
final BigInteger digest = new BigInteger(1,md5.digest());
// Pad the digest with blanks, 32 wide.
String hex = String.format(
    // See: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
    // Format: %[argument_index$][flags][width]conversion
    // Conversion: 'x', 'X'  integral    The result is formatted as a hexadecimal integer
    "%1$32x",
    digest
);
// Replace the blank padding with 0s.
hex = hex.replace(" ","0");
System.out.println(hex);
 7
Author: Nthalk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-29 20:58:09

Wiem, że ten wątek jest dość stary i pierwotne pytanie dotyczyło łatwego rozwiązania, ale jeśli ma być naprawdę szybki, powinieneś użyć tablicy znaków.

public static String pad(String str, int size, char padChar)
{
    if (str.length() < size)
    {
        char[] temp = new char[size];
        int i = 0;

        while (i < str.length())
        {
            temp[i] = str.charAt(i);
            i++;
        }

        while (i < size)
        {
            temp[i] = padChar;
            i++;
        }

        str = new String(temp);
    }

    return str;
}

Rozwiązanie formatera nie jest optymalne. po prostu budowanie formatu string tworzy 2 nowe ciągi.

Rozwiązanie Apache ' a można poprawić inicjalizując SB z docelowym rozmiarem, więc zastąpienie poniżej

StringBuffer padded = new StringBuffer(str); 

Z

StringBuffer padded = new StringBuffer(pad); 
padded.append(value);
Uniemożliwiłoby wzrost wewnętrznego bufora SB.
 6
Author: ck.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-28 14:34:48

Tutaj jest inny sposób, aby pad w prawo:

// put the number of spaces, or any character you like, in your paddedString

String paddedString = "--------------------";

String myStringToBePadded = "I like donuts";

myStringToBePadded = myStringToBePadded + paddedString.substring(myStringToBePadded.length());

//result:
myStringToBePadded = "I like donuts-------";
 5
Author: fawsha1,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-21 17:40:38

Możesz zmniejszyć narzut na wywołanie, zachowując dane wypełnienia, zamiast je przebudowywać za każdym razem:

public class RightPadder {

    private int length;
    private String padding;

    public RightPadder(int length, String pad) {
        this.length = length;
        StringBuilder sb = new StringBuilder(pad);
        while (sb.length() < length) {
            sb.append(sb);
        }
        padding = sb.toString();
   }

    public String pad(String s) {
        return (s.length() < length ? s + padding : s).substring(0, length);
    }

}

Jako alternatywę można ustawić długość wyniku jako parametr metody pad(...). W takim przypadku wykonaj korektę ukrytego wypełnienia w tej metodzie zamiast w konstruktorze.

(Podpowiedź: aby uzyskać dodatkowy kredyt, zrób to bezpiecznie! ;-)

 4
Author: joel.neely,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-12-23 14:25:42

Możesz użyć wbudowanych w StringBuilder metod append() i insert() , dla wypełnienia o zmiennej długości strun:

AbstractStringBuilder append(CharSequence s, int start, int end) ;

Na Przykład:

private static final String  MAX_STRING = "                    "; //20 spaces

    Set<StringBuilder> set= new HashSet<StringBuilder>();
    set.add(new StringBuilder("12345678"));
    set.add(new StringBuilder("123456789"));
    set.add(new StringBuilder("1234567811"));
    set.add(new StringBuilder("12345678123"));
    set.add(new StringBuilder("1234567812234"));
    set.add(new StringBuilder("1234567812222"));
    set.add(new StringBuilder("12345678122334"));

    for(StringBuilder padMe: set)
        padMe.append(MAX_STRING, padMe.length(), MAX_STRING.length());
 2
Author: ef_oren,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-08-24 10:55:49

To działa:

"".format("%1$-" + 9 + "s", "XXX").replaceAll(" ", "0")

Wypełni Twój ciąg XXX do 9 znaków białymi spacjami. Następnie wszystkie spacje zostaną zastąpione przez 0. Możesz zmienić białe znaki i 0 na dowolne...

 2
Author: Sebastian S.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-11 14:30:17
public static String padLeft(String in, int size, char padChar) {                
    if (in.length() <= size) {
        char[] temp = new char[size];
        /* Llenado Array con el padChar*/
        for(int i =0;i<size;i++){
            temp[i]= padChar;
        }
        int posIniTemp = size-in.length();
        for(int i=0;i<in.length();i++){
            temp[posIniTemp]=in.charAt(i);
            posIniTemp++;
        }            
        return new String(temp);
    }
    return "";
}
 2
Author: Marlon Tarax,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-24 17:36:51

Zostawmy odpowiedź na niektóre przypadki, które musisz podać lewy / prawy padding (lub przedrostek/sufiks lub spacje) przed połączeniem z innym łańcuchem i nie chcesz testować długości lub jakiegokolwiek warunku if.

To samo do wybranej odpowiedzi, wolałbym StringUtils z Apache Commons, ale używając tego sposobu:

StringUtils.defaultString(StringUtils.leftPad(myString, 1))

Wyjaśnij:

  • myString: łańcuch, który wprowadzam, może być null
  • StringUtils.leftPad(myString, 1): Jeśli string jest null, to polecenie zwróci null too
  • następnie użyj defaultString, Aby Dać pusty łańcuch, aby zapobiec konkatenacji null
 2
Author: Osify,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-29 13:37:21

Znalazłem to na Dzone

Pad z zerami:

String.format("|%020d|", 93); // prints: |00000000000000000093|
 2
Author: OJVM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-26 19:20:30

java.util.Formatter zrobi lewy i prawy padding. Nie ma potrzeby stosowania dziwnych zależności stron trzecich (czy chciałbyś dodać je do czegoś tak trywialnego).

[pominąłem szczegóły i zrobiłem ten post 'Community wiki', ponieważ nie jest to coś, czego potrzebuję.]

 1
Author: Tom Hawtin - tackline,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-12-23 14:58:42

@odpowiedzi ck i @Marlon Tarak są jedynymi, które używają char[], co dla aplikacji, które mają kilka wywołań metod padding na sekundę, jest najlepszym podejściem. Jednak nie wykorzystują one żadnej optymalizacji manipulacji tablicami i są trochę nadpisane jak na mój gust; można to zrobić za pomocą żadnych pętli.

public static String pad(String source, char fill, int length, boolean right){
    if(source.length() > length) return source;
    char[] out = new char[length];
    if(right){
        System.arraycopy(source.toCharArray(), 0, out, 0, source.length());
        Arrays.fill(out, source.length(), length, fill);
    }else{
        int sourceOffset = length - source.length();
        System.arraycopy(source.toCharArray(), 0, out, sourceOffset, source.length());
        Arrays.fill(out, 0, sourceOffset, fill);
    }
    return new String(out);
}

Prosta metoda badania:

public static void main(String... args){
    System.out.println("012345678901234567890123456789");
    System.out.println(pad("cats", ' ', 30, true));
    System.out.println(pad("cats", ' ', 30, false));
    System.out.println(pad("cats", ' ', 20, false));
    System.out.println(pad("cats", '$', 30, true));
    System.out.println(pad("too long for your own good, buddy", '#', 30, true));
}

Wyjścia:

012345678901234567890123456789
cats                          
                          cats
                cats
cats$$$$$$$$$$$$$$$$$$$$$$$$$$
too long for your own good, buddy 
 1
Author: ndm13,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-11 20:45:37

Użyj tej funkcji.

private String leftPadding(String word, int length, char ch) {
   return (length > word.length()) ? leftPadding(ch + word, length, ch) : word;
}

Jak używać?

leftPadding(month, 2, '0');

Wyjście: 01 02 03 04 .. 11 12

 1
Author: Samet öztoprak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-02 09:51:56

Proste rozwiązanie bez żadnego API będzie wyglądać następująco:

public String pad(String num, int len){
    if(len-num.length() <=0) return num;
    StringBuffer sb = new StringBuffer();
    for(i=0; i<(len-num.length()); i++){
        sb.append("0");
    }
    sb.append(num);
    return sb.toString();
}
 0
Author: Shashank Shekhar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-17 13:07:34

Java oneliners, no fancy library.

// 6 characters padding example
String pad = "******";
// testcases for 0, 4, 8 characters
String input = "" | "abcd" | "abcdefgh"

Pad Lewy, nie ograniczaj

result = pad.substring(Math.min(input.length(),pad.length())) + input;
results: "******" | "**abcd" | "abcdefgh"

Pad Prawy, nie ograniczaj

result = input + pad.substring(Math.min(input.length(),pad.length()));
results: "******" | "abcd**" | "abcdefgh"

Pad Lewy, ograniczenie do długości pad

result = (pad + input).substring(input.length(), input.length() + pad.length());
results: "******" | "**abcd" | "cdefgh"

Prawa Podkładka, ograniczenie do długości podkładki

result = (input + pad).substring(0, pad.length());
results: "******" | "abcd**" | "abcdef"
 0
Author: leo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-31 21:49:38

Wszystkie operacje string zazwyczaj muszą być bardzo wydajne - szczególnie jeśli pracujesz z dużymi zestawami danych. Chciałem coś, co jest szybkie i elastyczne, podobne do tego, co dostaniesz w PLSQL Pad polecenia. Poza tym, nie chcę zawierać Wielkiej lib tylko dla jednej małej rzeczy. Z tych względów żadne z tych rozwiązań nie było zadowalające. To są rozwiązania, które wymyśliłem, które miały najlepsze wyniki na ławce, jeśli ktoś może to poprawić, proszę o dodanie swojego skomentuj.

public static char[] lpad(char[] pStringChar, int pTotalLength, char pPad) {
    if (pStringChar.length < pTotalLength) {
        char[] retChar = new char[pTotalLength];
        int padIdx = pTotalLength - pStringChar.length;
        Arrays.fill(retChar, 0, padIdx, pPad);
        System.arraycopy(pStringChar, 0, retChar, padIdx, pStringChar.length);
        return retChar;
    } else {
        return pStringChar;
    }
}
  • uwaga jest wywoływana ciągiem znaków.toCharArray () i wynik można skonwertować na łańcuch znaków z nowym łańcuchem znaków ((char []) wynik). Powodem tego jest to, że jeśli zastosujesz wiele operacji, możesz wykonać je wszystkie na znakach [] i nie konwertować między formatami - za kulisami ciąg znaków jest przechowywany jako znak []. Gdyby te operacje były włączone do samej klasy String, byłyby dwa razy bardziej wydajne - szybkość i pamięć.
 0
Author: EarlB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-14 07:25:35

Wiele osób ma kilka bardzo ciekawych technik, ale lubię to proste, więc idę z tym:

public static String padRight(String s, int n, char padding){
    StringBuilder builder = new StringBuilder(s.length() + n);
    builder.append(s);
    for(int i = 0; i < n; i++){
        builder.append(padding);
    }
    return builder.toString();
}

public static String padLeft(String s, int n,  char padding) {
    StringBuilder builder = new StringBuilder(s.length() + n);
    for(int i = 0; i < n; i++){
        builder.append(Character.toString(padding));
    }
    return builder.append(s).toString();
}

public static String pad(String s, int n, char padding){
    StringBuilder pad = new StringBuilder(s.length() + n * 2);
    StringBuilder value = new StringBuilder(n);
    for(int i = 0; i < n; i++){
        pad.append(padding);
    }
    return value.append(pad).append(s).append(pad).toString();
}
 0
Author: Aelphaeis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-17 15:24:41

Prostym rozwiązaniem byłoby:

package nl;
public class Padder {
    public static void main(String[] args) {
        String s = "123" ;
        System.out.println("#"+("     " + s).substring(s.length())+"#");
    }
}
 -1
Author: Hans Andeweg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-19 12:24:53

Jak to jest

String to "hello", A wymagane wypełnienie to 15 z " 0 " lewym padem

String ax="Hello";
while(ax.length() < 15) ax="0"+ax;
 -2
Author: Satwant,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-28 11:53:39