SNIPPET, java.lang.StringBuilder
SNIPPET, java.lang.StringBuilder
This class defines a mutable sequence of characters. It was created as a drop-in replacement for StringBuffer class in places where the StringBuffer would be used for single threaded actions.
The principal operations in a StringBuilder are the append and insert methods which are overloaded and accept data of any type. A given datum is effectively converted to a string and the characters of that string inserted or appended to the StringBuilder where the append method add these characters at the end of the builder and the insert method at a specified point.
Here is a simple class, BuilderExample, that is based on the principles of the StringBuilder class.
package transkawa;
class BuilderExample {
static StringBuilder stringchain = new StringBuilder("A");
static final String initialchain = stringchain.toString();
String spaces = " ";
static String current="Current string chain: ";
//to append strings in this class, first attach a space
//then attach the string. Append always at the last position
void appendString(String str){
stringchain.append(spaces);
stringchain.append(str);
}
//this method appends a char without spaces
void appendChar(char ch){
stringchain.append(ch);
}
//insertString at any position before the last string in chain
void insertString(String str, String insertbefore){
int theindex = stringchain.indexOf(insertbefore);
stringchain.insert(theindex, str);
theindex += str.length();
stringchain.insert(theindex, spaces);
}
//properties method
int propMethod(char ch){
int resultvar = 0;
for (int i=0; i
resultvar +=1;
}
}
return resultvar;
}
public static void main(String[] args) {
//an instance of our class
BuilderExample build = new BuilderExample();
//on instantiating the string contains only "A"
System.out.println("Initial chain is "+initialchain);
//we're appending the string "Teaching" to the chain
build.appendString("Teaching");
System.out.println(current+BuilderExample.stringchain);
//we'll insert a string at a chosen position
build.insertString("Tremendous", "Teaching");
System.out.println(current+BuilderExample.stringchain);
//let's add "Tool" after "Teaching"
build.appendString("Tool");
System.out.println(current+BuilderExample.stringchain);
//suppose we made a mistake, we didn't insert '!' in "Tool"
build.appendChar('!');
System.out.println(current+BuilderExample.stringchain);
//if we want to know the properties of the string built
System.out.print("There are "+(build.propMethod(' ')+1)+"
words");
System.out.println(" and
+BuilderExample.stringchain.length()+" characters in the chain");
}
}
Enjoy!
No comments:
Post a Comment