Reputation: 23
I have 3 buttons: "Q", "W" and "E". When clicked they should append their letter to a StringBuilder
. Like this:
StringBuilder s = new StringBuilder();
(When "Q" button is clicked):
s.append("q");
(When "W" button clicked):
s.append("w");
But what I want is to have a maximum of 3 characters to be in the StringBuilder
.
3 digits after reaching the initial character of a key is pressed at the end wiper and write a new one. After the StringBuilder
reaches three characters, it will remove the initial one and append the next. Like marquee.
Example:
StringBuilder is "QWW",
When E button clicked StringBuilder must be "WWE".
When W button clicked StringBuilder must be "WEW".
Upvotes: 2
Views: 182
Reputation: 2289
The alternative way is to use char array
char[] arr = new char[]{'','',''};
...
private void appendChar(char a){
for(int i=0;i<arr.length-1;i++){
arr[i] = arr[i+1];
}
arr[arr.length-1] = a;
}
And finally:
String res = new String(arr);
Upvotes: 1
Reputation: 13066
Here you go:
StringBuilder sBuilder = new StringBuilder();
public void prepareBuilder(String str)
{
if (sBuilder.length() < 3)
sBuilder.append(str);
else
{
sBuilder.deleteCharAt(0);
sBuilder.append(str);
}
}
Upvotes: 0
Reputation: 117589
Use StringBuilder#deleteCharAt(int index)
:
public static void addToStringBuilder(StringBuilder sb, int max, char letter)
{
if(sb.length() >= max) sb.deleteCharAt(0);
sb.append(letter);
}
For example:
StringBuilder sb = new StringBuilder();
addToStringBuilder(sb, 3, 'Q');
System.out.println(sb);
addToStringBuilder(sb, 3, 'W');
System.out.println(sb);
addToStringBuilder(sb, 3, 'W');
System.out.println(sb);
addToStringBuilder(sb, 3, 'E');
System.out.println(sb);
addToStringBuilder(sb, 3, 'W');
System.out.println(sb);
OUTPUT:
Q
QW
QWW
WWE
WEW
Upvotes: 0