• 0

JAVA: Multiply a character


Question

5 answers to this question

Recommended Posts

  • 0
  arigold said:
thanks, guessing x cant be replaced with " "; a space, just tried it didnt work.

It would work, but it would be better to use a StringBuffer.

char repChar = ' ';
StringBuffer buffer = new StringBuffer();
for(int i=0;i<100;i++) {
  buffer.append(repChar);
}

  • 0

Adding chars to a String actually creates a new String each time, so if it's going to be a long String that's going to be inefficient. StringBuffer is better because StringBuffers are mutable - ie you don't create a new one each time provided you use append(...).

Probably the cleanest is to create a char array, something like (not checked for typos!):

public String create(int n, char c) {
   char[] temp = new char[n];
   for (int i=0; i++, i<n) char[i] = c;
   return new String(temp);
}

Alternatively, depending on what you want to do with it later, just keep the array of chars and don't bother to put it in a String

public char[] create(int n, char c) {
   char[] temp = new char[n];
   for (int i=0; i++, i<n) char[i] = c;
   return temp;
}

Edited by JamesCherrill
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.