n 개의 문자로 문자열 만들기
Java에서 지정된 수의 지정된 문자로 문자열을 만드는 방법이 있습니까? 필자의 경우 공백이 10 개인 문자열을 만들어야합니다. 내 현재 코드는 다음과 같습니다
StringBuffer outputBuffer = new StringBuffer(length);
for (int i = 0; i < length; i++){
outputBuffer.append(" ");
}
return outputBuffer.toString();
같은 것을 성취하는 더 좋은 방법이 있습니까? 특히 나는 (실행 측면에서) 빠른 것을 원합니다.
for 루프는 컴파일러에 의해 최적화됩니다. 당신과 같은 경우에는 스스로 최적화 할 필요가 없습니다. 컴파일러를 신뢰하십시오. :)
편집 : 당신이 방금했던 것과 같은 방식으로 코딩 된 것보다 n 개의 공백 문자로 문자열을 만드는 방법이 있다면 Btw.
StringAPI를 사용하는 가장 짧은 코드는 다음과 같습니다.
String space10 = new String(new char[10]).replace('\0', ' ');
System.out.println("[" + space10 + "]");
// prints "[ ]"
직접 인스턴스화하지 않고 방법으로 char:
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', ' ' );
}
다음을 사용하여 호출하십시오.
System.out.printf( "[%s]%n", spaces( 10 ) );
흠 이제 내가 생각할 것입니다 Arrays.fill.
char[] charArray = new char[length];
Arrays.fill(charArray, ' ');
String str = new String(charArray);
물론, fill메소드가 코드와 동일한 작업을 수행 한다고 가정 하므로 아마도 거의 동일하게 수행되지만 최소한 줄 수는 적습니다.
나는 루프를 손으로 쓰지 말 것을 강력히 권합니다. 당신은 프로그래밍 경력 동안 반복해서 그렇게 할 것입니다. 코드를 읽는 사람들 (여러분을 포함)은 루프의 의미를 소화하기 위해 몇 초 만이라도 시간을 투자해야합니다.
대신 재사용 만 수행하는 코드를 제공하는 사용 가능한 라이브러리 중 하나 같은 StringUtils.repeat에서 아파치 코 몬즈 랭 :
StringUtils.repeat(' ', length);
그렇게하면 성능에 신경 쓰지 않아도되므로 StringBuilder컴파일러 최적화 등 의 모든 세부 사항 이 숨겨집니다. 함수가 느리게 나오면 라이브러리의 버그 일 것입니다.
로 자바 (11) 가 더 쉽게된다 :
" ".repeat(length);
Java 8에서는 다음을 사용할 수 있습니다 String.join.
String.join("", Collections.nCopies(n, s));
공백 만 원하면 어떻습니까?
String spaces = (n==0)?"":String.format("%"+n+"s", "");
abs (n) 공백이 발생합니다.
나는 이것이 가능한 코드가 아니라고 생각하고 Guava Joiner 클래스를 사용합니다.
결합 자 .on ( ""). join ( Collections.nCopies (10, ""));
빠른 지수화 알고리즘을 기반으로 한 나의 기여.
/**
* Repeats the given {@link String} n times.
*
* @param str
* the {@link String} to repeat.
* @param n
* the repetition count.
* @throws IllegalArgumentException
* when the given repetition count is smaller than zero.
* @return the given {@link String} repeated n times.
*/
public static String repeat(String str, int n) {
if (n < 0)
throw new IllegalArgumentException(
"the given repetition count is smaller than zero!");
else if (n == 0)
return "";
else if (n == 1)
return str;
else if (n % 2 == 0) {
String s = repeat(str, n / 2);
return s.concat(s);
} else
return str.concat(repeat(str, n - 1));
}
다른 두 가지 접근 방식에 대해 알고리즘을 테스트했습니다.
String.concat()문자열을 연결 하는 데 사용 되는 정규 for 루프- a를 사용하여 규칙적인 for 루프
StringBuilder
테스트 코드 (for 루프를 사용하여 연결 String.concat()하고 크게 느리게 n되므로 5 번째 반복 후에 생략했습니다).
/**
* Test the string concatenation operation.
*
* @param args
*/
public static void main(String[] args) {
long startTime;
String str = " ";
int n = 1;
for (int j = 0; j < 9; ++j) {
n *= 10;
System.out.format("Performing test with n=%d\n", n);
startTime = System.currentTimeMillis();
StringUtil.repeat(str, n);
System.out
.format("\tStringUtil.repeat() concatenation performed in %d milliseconds\n",
System.currentTimeMillis() - startTime);
if (j <5) {
startTime = System.currentTimeMillis();
String string = "";
for (int i = 0; i < n; ++i)
string = string.concat(str);
System.out
.format("\tString.concat() concatenation performed in %d milliseconds\n",
System.currentTimeMillis() - startTime);
} else
System.out
.format("\tString.concat() concatenation performed in x milliseconds\n");
startTime = System.currentTimeMillis();
StringBuilder b = new StringBuilder();
for (int i = 0; i < n; ++i)
b.append(str);
b.toString();
System.out
.format("\tStringBuilder.append() concatenation performed in %d milliseconds\n",
System.currentTimeMillis() - startTime);
}
}
결과 :
Performing test with n=10
StringUtil.repeat() concatenation performed in 0 milliseconds
String.concat() concatenation performed in 0 milliseconds
StringBuilder.append() concatenation performed in 0 milliseconds
Performing test with n=100
StringUtil.repeat() concatenation performed in 0 milliseconds
String.concat() concatenation performed in 1 milliseconds
StringBuilder.append() concatenation performed in 0 milliseconds
Performing test with n=1000
StringUtil.repeat() concatenation performed in 0 milliseconds
String.concat() concatenation performed in 1 milliseconds
StringBuilder.append() concatenation performed in 1 milliseconds
Performing test with n=10000
StringUtil.repeat() concatenation performed in 0 milliseconds
String.concat() concatenation performed in 43 milliseconds
StringBuilder.append() concatenation performed in 5 milliseconds
Performing test with n=100000
StringUtil.repeat() concatenation performed in 0 milliseconds
String.concat() concatenation performed in 1579 milliseconds
StringBuilder.append() concatenation performed in 1 milliseconds
Performing test with n=1000000
StringUtil.repeat() concatenation performed in 0 milliseconds
String.concat() concatenation performed in x milliseconds
StringBuilder.append() concatenation performed in 10 milliseconds
Performing test with n=10000000
StringUtil.repeat() concatenation performed in 7 milliseconds
String.concat() concatenation performed in x milliseconds
StringBuilder.append() concatenation performed in 112 milliseconds
Performing test with n=100000000
StringUtil.repeat() concatenation performed in 80 milliseconds
String.concat() concatenation performed in x milliseconds
StringBuilder.append() concatenation performed in 1107 milliseconds
Performing test with n=1000000000
StringUtil.repeat() concatenation performed in 1372 milliseconds
String.concat() concatenation performed in x milliseconds
StringBuilder.append() concatenation performed in 12125 milliseconds
결론:
- 큰 경우
n-재귀 접근법을 사용하십시오. - 작은
nfor 루프의 속도는 충분합니다
String.formatN 개의 공간을 생성 하기 위해 표준 기능을 사용할 수 있습니다 . 예를 들면 다음과 같습니다.
String.format("%5c", ' ');
공백이 5 개인 문자열을 만듭니다.
또는
int count = 15;
String fifteenSpacebars = String.format("%" + count + "c", ' ');
15 개의 스페이스 바 문자열을 만듭니다.
다른 기호를 반복하려면 공백을 원하는 기호로 바꿔야합니다.
int count = 7;
char mySymbol = '#';
System.out.println(String.format("%" + count + "c", ' ').replaceAll("\\ ", "\\" + mySymbol));
산출:
#######
우리가 고려할 때 :
String c = "c"; // character to repeat, for empty it would be " ";
int n = 4; // number of times to repeat
String EMPTY_STRING = ""; // empty string (can be put in utility class)
Java 8 (스트림 사용)
String resultOne = IntStream.range(0,n)
.mapToObj(i->c).collect(Collectors.joining(EMPTY_STRING)); // cccc
Java 8 (nCopies 사용)
String resultTwo = String.join(EMPTY_STRING, Collections.nCopies(n, c)); //cccc
Java 11부터는 간단히 String.repeat(count)문제를 해결하는 데 사용할 수 있습니다.
이 문자열을 반복해서 연결 한 값을 가진 문자열을 반환합니다
count.이 문자열이 비어 있거나
count0이면 빈 문자열이 반환됩니다.
따라서 루프 대신 코드는 다음과 같습니다.
" ".repeat(length);
이건 어때요?
char[] bytes = new char[length];
Arrays.fill(bytes, ' ');
String str = new String(bytes);
RandomStringUtils 에는 주어진 입력 크기에서 문자열을 작성하는 규정이 있습니다. 캔 트는 속도에 대해 언급하지만 하나의 라이너입니다.
RandomStringUtils.random(5,"\t");
출력을 만듭니다
\ t \ t \ t \ t \ t
코드에서 \ 0 을보고 싶지 않으면 선호됩니다 .
StringUtils 사용 : StringUtils.repeat ( '', 10)
대부분의 경우 문자열은 특정 길이까지만 필요합니다 (예 : 100 칸). 인덱스 번호가 공백으로 채워진 문자열의 크기와 같은 문자열 배열을 준비하고 필요한 길이가 한계 내에 있거나 문자열이 경계를 벗어나면 필요에 따라 문자열을 조회 할 수 있습니다.
Stream.generate(() -> ch).limit(n).collect(joining());
어디:
import static java.util.stream.Collectors.joining;
import java.util.stream.Stream;
...
String ch = " ";
int n = 10;
Stream
.generate(() -> ch)
.limit(n)
.collect(joining());
그냥 당신의 StringBuffer를 교체 하여 StringBuilder . 그것을 이길 어렵다.
If your length is a big number, you might implement some more efficient (but more clumsy) self-appendding, duplicating the length in each iteration:
public static String dummyString(char c, int len) {
if( len < 1 ) return "";
StringBuilder sb = new StringBuilder(len).append(c);
int remnant = len - sb.length();
while(remnant > 0) {
if( remnant >= sb.length() ) sb.append(sb);
else sb.append(sb.subSequence(0, remnant));
remnant = len - sb.length();
}
return sb.toString();
}
Also, you might try the Arrays.fill() aproach (FrustratedWithFormsDesigner's answer).
You can replace StringBuffer with StringBuilder ( the latter is not synchronized, may be a faster in a single thread app )
And you can create the StringBuilder instance once, instead of creating it each time you need it.
Something like this:
class BuildString {
private final StringBuilder builder = new StringBuilder();
public String stringOf( char c , int times ) {
for( int i = 0 ; i < times ; i++ ) {
builder.append( c );
}
String result = builder.toString();
builder.delete( 0 , builder.length() -1 );
return result;
}
}
And use it like this:
BuildString createA = new BuildString();
String empty = createA.stringOf( ' ', 10 );
If you hold your createA as a instance variable, you may save time creating instances.
This is not thread safe, if you have multi threads, each thread should have its own copy.
For good performance, combine answers from aznilamir and from FrustratedWithFormsDesigner
private static final String BLANKS = " ";
private static String getBlankLine( int length )
{
if( length <= BLANKS.length() )
{
return BLANKS.substring( 0, length );
}
else
{
char[] array = new char[ length ];
Arrays.fill( array, ' ' );
return new String( array );
}
}
Adjust size of BLANKS depending on your requirements. My specific BLANKS string is about 200 characters length.
Have a method like this. This appends required spaces at the end of the given String to make a given String to length of specific length.
public static String fillSpaces (String str) {
// the spaces string should contain spaces exceeding the max needed
String spaces = " ";
return str + spaces.substring(str.length());
}
The shortest solution with Guava:
Strings.repeat(" ", len)
Via Simple way to repeat a String in java.
A simple method like below can also be used
public static String padString(String str, int leng,char chr) {
for (int i = str.length(); i <= leng; i++)
str += chr;
return str;
}
how about this?
public String fillSpaces(int len) {
/* the spaces string should contain spaces exceeding the max needed */
String spaces = " ";
return spaces.substring(0,len);
}
EDIT: I've written a simple code to test the concept and here what i found.
Method 1: adding single space in a loop:
public String execLoopSingleSpace(int len){
StringBuilder sb = new StringBuilder();
for(int i=0; i < len; i++) {
sb.append(' ');
}
return sb.toString();
}
Method 2: append 100 spaces and loop, then substring:
public String execLoopHundredSpaces(int len){
StringBuilder sb = new StringBuilder(" ")
.append(" ").append(" ").append(" ")
.append(" ").append(" ").append(" ")
.append(" ").append(" ").append(" ");
for (int i=0; i < len/100 ; i++) {
sb.append(" ")
.append(" ").append(" ").append(" ")
.append(" ").append(" ").append(" ")
.append(" ").append(" ").append(" ");
}
return sb.toString().substring(0,len);
}
The result I get creating 12,345,678 spaces:
C:\docs\Projects> java FillSpace 12345678
method 1: append single spaces for 12345678 times. Time taken is **234ms**. Length of String is 12345678
method 2: append 100 spaces for 123456 times. Time taken is **141ms**. Length of String is 12345678
Process java exited with code 0
and for 10,000,000 spaces:
C:\docs\Projects> java FillSpace 10000000
method 1: append single spaces for 10000000 times. Time taken is **157ms**. Length of String is 10000000
method 2: append 100 spaces for 100000 times. Time taken is **109ms**. Length of String is 10000000
Process java exited with code 0
combining direct allocation and iteration always takes less time, on average 60ms less when creating huge spaces. For smaller sizes, both results are negligible.
But please continue to comment :-)
I know of no built-in method for what you're asking about. However, for a small fixed length like 10, your method should be plenty fast.
참고URL : https://stackoverflow.com/questions/2804827/create-a-string-with-n-characters
'IT story' 카테고리의 다른 글
| 제약 조건으로 열을 삭제하는 방법은 무엇입니까? (0) | 2020.07.12 |
|---|---|
| MySQL 날짜 형식 DD / MM / YYYY 선택 쿼리? (0) | 2020.07.12 |
| jQuery UI 자동 완성에서 결과 제한 (0) | 2020.07.12 |
| .dex 파일의 메소드 참조 수는 64k API 17을 초과 할 수 없습니다 (0) | 2020.07.12 |
| 오류 : 항목의 널값 : incrementalFolder = null (0) | 2020.07.12 |