2つのスタック(left
とright
)を持つテキストエディタバッファhwの割り当てがあります。すべては、ほとんどの場合、それが想定されている方法で動作します。しかし、私が抱えている問題は、それがあまりにも多くの空白を返すということです。私は具体的にテキストを返すためにtoString()
メソッドを記入しようとしています。例えば リターンテキストを印刷:文字間、単一のスペースと、各単語の間に二重のスペースがありますあまりにも多くの空白を削除するtoStringメソッド
T h e r e i s g r a n d e u r i n t h i s v i e w o f l i f e ,
。どのように私の文字列を返すように、言葉だけの間で1つの空白を除去しながら、私は、文字間の空白を削除するには:
There is grandeur in this view of life,
public class Buffer {
private Stack<Character> left; // chars left of cursor
private Stack<Character> right; // chars right of cursor
// Create an empty buffer.
public Buffer() {
left = new Stack<Character>();
right = new Stack<Character>();
}
// Insert c at the cursor position.
public void insert(char c) {
left.push(c);
}
// Delete and return the character at the cursor.
public char delete() {
if (!right.isEmpty()){
return right.pop();
}else return 0;
}
// Move the cursor k positions to the left.
public void left(int k) {
while (!left.isEmpty() && --k >= 0){
right.push(left.pop());
}
}
// Move the cursor k positions to the right.
public void right(int k) {
while (!right.isEmpty() && --k >=0){
left.push(right.pop());
}
}
// Return the number of characters in the buffer.
public int size() {
return left.size()+right.size();
}
// Return a string representation of the buffer with a "|" character (not
// part of the buffer) at the cursor position.
public String toString() {
String a = (left+"|"+right);
return a;
}
// Test client (DO NOT EDIT).
public static void main(String[] args) {
Buffer buf = new Buffer();
String s = "There is grandeur in this view of life, with its "
+ "several powers, having been originally breathed into a few "
+ "forms or into one; and that, whilst this planet has gone "
+ "cycling on according to the fixed law of gravity, from so "
+ "simple a beginning endless forms most beautiful and most "
+ "wonderful have been, and are being, evolved. ~ "
+ "Charles Darwin, The Origin of Species";
for (int i = 0; i < s.length(); i++) {
buf.insert(s.charAt(i));
}
buf.left(buf.size());
buf.right(97);
s = "by the Creator ";
for (int i = 0; i < s.length(); i++) {
buf.insert(s.charAt(i));
}
buf.right(228);
buf.delete();
buf.insert('-');
buf.insert('-');
buf.left(342);
StdOut.println(buf);
}
}
[最小限で完全であり、検証可能な例](http://stackoverflow.com/help/mcve)を投稿してください。 – MikeCAT
あなたは、このサイトのルールに従って、あなたの質問をあなたの問題を解決するために最善の善意の試みを示すべきです。 [宿題に関する質問と回答方法](http://meta.stackexchange.com/a/10812/162852)もご覧ください。この情報は、質問が宿題や家事のためであるかどうかにかかわらず有効です(自習)。 –
toString()メソッドのコードは何ですか? –