SORU
10 Mayıs 2010, PAZARTESİ


N karakter içeren bir dize oluşturun

Java bir şekilde belirtilen bir karakter belirli bir dizi ile bir dize oluşturmak için var mı? Benim durumumda 10 boşluk içeren bir dize oluşturun. Benim şu anki kod:

StringBuffer outputBuffer = new StringBuffer(length);
for (int i = 0; i < length; i  ){
   outputBuffer.append(" ");
}
return outputBuffer.toString();

Daha iyi bir şekilde aynı şeyi yapmak için var. Özellikle hızlı bir şey (yürütme anlamında) istiyorum.

CEVAP
11 Mayıs 2010, Salı


Muhtemelen en kısa kod kullanarak String API, yalnızca:

String space10 = new String(new char[10]).replace('\0', ' ');

System.out.println("["   space10   "]");
// prints "[          ]"

Bir yöntem olarak, doğrudan başlatmasını char: olmadan

import java.nio.CharBuffer;

/**
 * Creates a string of spaces that is 'spaces' spaces long.
 *
 * @param spaces The number of spaces to add to the string.
 */
public String spaces( int spaces ) {
  return CharBuffer.allocate( spaces ).toString().replace( '\0', ' ' );
}

Kullanarak çağırmak:

System.out.printf( "[%s]%n", spaces( 10 ) );

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Greater Than Gatsby Photoshop Actions & Lightroom Presets

    Greater Than

    11 ŞUBAT 2013
  • Tahir Jahi

    Tahir Jahi

    6 Mart 2006
  • Troy Hunt

    Troy Hunt

    29 EYLÜL 2011