Two code files below : the actual logic & the test logic.
Core Logic
package stringBuilder;
public class NoksStringBuilder {
//initial capacity
private static final int INITIAL_SIZE = 3;
String[] stringList = new String[INITIAL_SIZE];
//number of strings in the builder currently
int size = 0;
//total number of chars in the builder , sum total of length of each string
int characterCount = 0;
public void add(String s){
if(size < stringList.length){
stringList[size++] = s;
characterCount += s.length();
}
else{
String[] temp = new String[stringList.length*2];
for(int i =0 ; i< stringList.length; i++){
temp[i] = stringList[i];
}
stringList = temp;
add(s);
}
}
public String toString(){
char[] output = new char[characterCount];
int outputIndex = 0;
for(int i = 0; i < size; i++){
for(int j = 0; j < stringList[i].length(); j++){
output[outputIndex++] = stringList[i].charAt(j);
}
}
return new String(output);
}
}
Test Class
package stringBuilder;
import java.util.Scanner;
public class Test {
public static void main(String[] args){
NoksStringBuilder stringBuilder = new NoksStringBuilder();
Scanner inputScanner = new Scanner(System.in);
int i = 0;
while(i != 3){
printMenu();
i = Integer.parseInt(inputScanner.nextLine());
if(i == 1){
System.out.println("Enter string");
stringBuilder.add(inputScanner.nextLine());
}
else if( i == 2){
System.out.println(stringBuilder.toString());
}
}
}
private static void printMenu() {
System.out.println("StringBuilder Options :");
System.out.println("1.Add");
System.out.println("2.ToString");
System.out.println("3.Quit");
}
}