Hello I have following method to display a promotion line when I comment a shoutbox:
public String getShoutboxUnderline(){
StringBuilder builder = new StringBuilder();
builder.append("watch");
builder.append("on");
builder.append("youtube");
builder.append(":");
builder.append("Mickey");
builder.append("en");
builder.append("de");
builder.append("stomende");
builder.append("drol");
return builder.toString();
}
But when I get it, I get watchonyoutube:mickeyendestomendedrol, which is without spaces. How do I get spaces in my Stringbuilder?
As of JDK 1.8, you can use a StringJoiner, which is more convenient in your case:
StringJoiner is used to construct a sequence of characters separated
by a delimiter and optionally starting with a supplied prefix and
ending with a supplied suffix.
StringJoiner joiner = new StringJoiner(" "); // Use 'space' as the delimiter
joiner.add("watch") // watch
.add("on") // watch on
.add("youtube") // watch on youtube
.add(":") // etc...
.add("Mickey")
.add("en")
.add("de")
.add("stomende")
.add("drol");
return joiner.toString();
This way, you will not need to add those spaces "manually".
Just invoke builder.append(" ") at the location of your preference.
E.g.
builder
.append("watch")
.append(" ")
.append("on")
...etc.
NB:
Using the fluent builder syntax here for convenience
You can also just append a space after each literal instead (save for the last one)
Cleaner way of doing it.
Create a class variable:
private static final String BLANK_SPACE=" ";
Now in you StringBuilder code ,append it where required:
StringBuilder builder = new StringBuilder();
builder.append("watch");
builder.append(BLANK_SPACE);
builder.append("on");
builder.append("youtube");
builder.append(":");
builder.append(BLANK_SPACE);
builder.append("Mickey");
builder.append("en");
builder.append("de");
builder.append(BLANK_SPACE);
builder.append("stomende");
builder.append("drol");
System.out.println(builder.toString());
A space is only a string containing the single character space.
So you can append it exactly as appending any other string.
StringBuilder builder = new StringBuilder();
builder.append("watch");
builder.append(" ");
builder.append("on");
builder.append(" ");
// and so on
Remember also that the append method returns the StringBuilder so it is possible to join appends one after the other as follow
StringBuilder builder = new StringBuilder();
builder.append("watch").append(" ");
builder.append("on").append(" ");
// and so on
You can use this, it's equivalent to using StringBuilder or StringJoiner, but smaller
public class StringUnifier {
String separator = "";
List<String> dataList = new ArrayList<>();
private String response = "";
StringUnifier(String separator) {
this.separator = separator;
}
StringUnifier add(String data) {
if (!data.isEmpty()) {
this.dataList.add(data);
}
return this;
}
#Override
public String toString() {
this.dataList.forEach(str -> {
this.response += (str + this.separator);
});
return this.response.substring(0, this.response.length() - this.separator.length());
}
}
MAIN
public class Main_Test {
public static void main(String[] args) {
StringUnifier stringUnifier = new StringUnifier(" ");
stringUnifier.add("columna1").add("columna2").add("columna3");
System.out.println(stringUnifier.toString());
}
}
RUN
output:
columna1 columna2 columna3
Related
I want to skip printing ", " in last iteration.
I want output like name, name, name
Output now i am getting is name, name, name,
StringBuffer stringBuffer = new StringBuffer();
for(MovieModel.Cast cast : movieModelList.get(position).getCastList()){
stringBuffer.append(cast.getName() + ", ");
}
You can append the comma before you append the name. Like this:
StringBuffer stringBuffer = new StringBuffer();
for(MovieModel.Cast cast : movieModelList.get(position).getCastList()){
if (stringBuffer.length() != 0) {
stringBuffer.append(",");
}
stringBuffer.append(cast.getName());
}
It's easier to insert the delimiter first. But, append the delimiter from a variable:
StringBuffer stringBuffer = new StringBuffer();
String delim = "";
for(MovieModel.Cast cast : movieModelList.get(position).getCastList()){
stringBuffer.append(delim);
stringBuffer.append(cast.getName());
delim = ",";
}
In this way, you don't append the , before the first element, but do before the subsequent elements.
A couple of notes:
Don't concatenate strings to append them to the buffer. This defeats the point of the buffer (somewhat, not entirely). Append one part, then append the other.
You almost certainly want to use a StringBuilder instead of StringBuffer:
As of release JDK 5, [StringBuffer] has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.
Why reinvent the wheel? Use StringUtils.join method from Apache Commons. Or you can inspire (copy+modify) from its sourcecode commons-lang-sources
// copied from https://commons.apache.org/proper/commons-lang/apidocs/src-html/org/apache/commons/lang3/StringUtils.html
public static String join(final Iterator<?> iterator, final String separator) {
// handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return EMPTY;
}
final Object first = iterator.next();
if (!iterator.hasNext()) {
return Objects.toString(first, "");
}
// two or more elements
final StringBuilder buf = new StringBuilder(STRING_BUILDER_SIZE); // Java default is 16, probably too small
if (first != null) {
buf.append(first);
}
while (iterator.hasNext()) {
if (separator != null) {
buf.append(separator);
}
final Object obj = iterator.next();
if (obj != null) {
buf.append(obj);
}
}
return buf.toString();
}
After the loop, just remove the trailing comma and space:
stringBuffer.delete(stringBuffer.length() - 2, stringBuffer.length());
Try
StringBuffer stringBuffer = new StringBuffer();
for(MovieModel.Cast cast : movieModelList.get(position).getCastList()){
stringBuffer.append(cast.getName());
stringBuffer.append(", ");
}
stringBuffer.delete(stringBuffer.length() - 2, stringBuffer.length());
I'm trying to tokenize some sentences. For example the sentences :
String sentence = "The sky is blue. A cat is #blue.";
I use the following command with Open nlp:
SimpleTokenizer tokenizer = SimpleTokenizer.INSTANCE;
String[] result = tokenizer.tokenize(sentence);
But I want opennlp considers '#' as a letter of a word. So '#blue#' will be a token.
How to do this ?
You just have to create a new Tokenizer object (implementing Tokenizer).
Tokenizer t = new Tokenizer() {
#Override
public Span[] tokenizePos(String arg0) {
}
#Override
public String[] tokenize(String arg0) {
}
};
Then, Copy/Paste the SimpleTokenizer code into thoses 2 functions.
And Associate the '#' to others alphanumericals values :
if (StringUtil.isWhitespace(c)) {
charType = CharacterEnum.WHITESPACE;
} else if (Character.isLetter(c) || c=='#') {
charType = CharacterEnum.ALPHABETIC;
} else if (Character.isDigit(c)) {
charType = CharacterEnum.NUMERIC;
} else {
charType = CharacterEnum.OTHER;
}
Maybe you are just being unlucky, try this:
public static void tokenize() throws InvalidFormatException, IOException {
InputStream is = new FileInputStream("models/en-token.bin");
TokenizerModel model = new TokenizerModel(is);
Tokenizer tokenizer = new TokenizerME(model);
String tokens[] = tokenizer.tokenize("The sky is blue. A cat is #blue. ");
for (String a : tokens)
System.out.println(a);
is.close();
}
As you can see, "#blue" is tokenized as a single token. And the intelligence of the Tokenizer remains.
For this to work you will need the "en-token.bin" model for this to work.
you could just try String[] tokens = sentence.split(" ");
split() is a method of String in java. Passing it a space (i.e. " ") will just give you all the tokens in the string delimited by a space
I have a string array variable which values changes continuously. Random arrays are generated from it. This is what i have:
String trans = Utility.GetColumnValue(testdata[k], "suggest_text_2");
The trans value changes continuously. How can i concatenate it with the previous values? How can i print every value of trans as it changes continuously? Do i need to use any buffer?
If you need the intermediate results, you will probably need something like this:
String yourOldString;
String freshString;
// other code which updates freshString
yourOldString = yourOldString + " " + freshString;
However if you do need to catch all updates but only print out the final result, use a StringBuilder:
private static final String WHITESPACE = " ";
String yourOldString;
String freshString;
StringBuilder builder = new StringBuilder();
builder.append(yourOldString);
// other code which updates freshString
builder.append(WHITESPACE);
builder.append(freshString);
// once everything is done:
String resultString = builder.toString();
String a = "foo";
String space = " ";
String b = "bar";
String c = a+space+b;
It's often best to use StringBuilder to concatenate strings:
String [] array { "fee", "fie", "foe", "fum" };
boolean firstTime = true;
StringBuilder sb = new StringBuilder(50);
for (String word : array) {
if (firstTime) {
firstTime = false;
} else {
sb.append(' ');
}
sb.append(word);
}
String finalResult = sb.toString();
System.out.println("string1 "+"string2");
Simply,
String trans = Utility.GetColumnValue(testdata[k], "suggest_text_2");
StringBuffer concat = new StringBuffer();
concat.append(test).append(" ");
Or,
StringBuffer concat = new StringBuffer();
concat.append(Utility.GetColumnValue(testdata[k], "suggest_text_2")).append(" ");
To concatenate/combine set of data.
for(String s: trans){
concat.append(s).append(" ");
}
String concatenation(like trans + " ") is slower than the StringBuffer append(). I strongly suggest you to use StringBuilder. Because when combinig String on the fly StringBuffer is created and then using toString() converts to String.
Here is nice blog post to read to learn about performance of these two.
I am inputting a string and I want to add the delimeters in that string to a different string and I was wondering how you would do that. This is the code I have at the moment.
StringTokenizer tokenizer = new StringTokenizer(input, "'.,><-=[]{}+!##$%^&*()~`;/?");
while (tokenizer.hasMoreTokens()){
//add delimeters to string here
}
Any help would be greatly appreciated(:
If you want StringTokenizer to return the delimiters it parses, you would need to add a flag to the constructor as shown here
StringTokenizer tokenizer = new StringTokenizer(input, "'.,><-=[]{}+!##$%^&*()~`;/?", true);
But if you are searching only for delimiters I dont think this is the right approach.
I don't think StringTokenizer is good for this task, try
StringBuilder sb = new StringBuilder();
for(char c : input.toCharArray()) {
if ("'.,><-=[]{}+!##$%^&*()~`;/?".indexOf(c) >= 0) {
sb.append(c);
}
}
I'm guessing you want to extract all the delimiters from the string and process them
String allTokens = "'.,><-=[]{}+!##$%^&*()~`;/?";
StringTokenizer tokenizer = new StringTokenizer(input, allTokens, true);
while(tokenizer.hasMoreTokens()) {
String nextToken = tokenizer.nextToken();
if(nextToken.length()==1 && allTokens.contains(nextToken)) {
//this token is a delimiter
//append to string or whatever you want to do with the delimiter
processDelimiter(nextToken);
}
}
Create a processDelimiter method in which you add the delimiter to a different string or perform any action you want.
This would even take care of repeated usage of delimeters
String input = "adfhkla.asijdf.';.akjsdhfkjsda";
String compDelims = "'.,><-=[]{}+!##$%^&*()~`;/?";
String delimsUsed = "";
for (char a : compDelims.toCharArray()) {
if (input.indexOf(a) > 0 && delimsUsed.indexOf(a) == -1) {
delimsUsed += a;
}
}
System.out.println("The delims used are " + delimsUsed);
So I essentially need to do this:
String text = "line1\n";
text += "line2\n";
text += "line3\n";
useString( text );
There is more involved, but that's the basic idea. Is there anything out there that might let me do something more along the lines of this though?
DesiredStringThinger text = new DesiredStringThinger();
text.append( "line1" );
text.append( "line2" );
text.append( "line3" );
useString( text.toString() );
Obviously, it does not need to work exactly like that, but I think I get the basic point across. There is always the option of writing a loop which processes the text myself, but it would be nice if there is a standard Java class out there that already does something like this rather than me needing to carry a class around between applications just so I can do something so trivial.
Thanks!
You can use a StringWriter wrapped in a PrintWriter:
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter, true);
writer.println("line1");
writer.println("line2");
writer.println("line3");
useString(stringWriter.toString());
AFAIK there's no library class that allows you to do so.
The following does the work though:
class DesiredStringThinger {
StringBuilder text = new StringBuilder();
public void append(String s) { text.append(s).append("\n"); }
#Override
public String toString() { return text.toString(); }
}
public String createString () {
StringBuilder sb = new StringBuilder ();
String txt = appendLine("firstline", sb).appendLine("2ndLine", sb).toString();
}
private StringBuilder appendLine (String line, StringBuilder sb) {
String lsp = System.getProperty("line.separator");
return sb.append (line).append (lsp);
}
Here's a Java 8 solution using a stream:
public class DesiredStringThinger {
private List<String> items = new ArrayList<>();
public void append(String s) {
items.add(s);
}
#Override
public String toString() {
return items.stream().collect(Collectors.joining("\n", "", "\n"));
}
}
You can use from Apache Commons the StringUtils.join helper. Which allows to build a String from a list. You can add the 'delimiter' character/string.
If you are willing to use external libraries, check out the Joiner in Guava.
Your code would go to something like
String result = Joiner.on("\n").join(parts);
where parts is an Iterable<String>.
Java SE 8
With Java SE 8, a couple of additional ways can be by:
Using String#join
Using Stream.
Demo:
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String[] arr = { "line1", "line2", "line3" };
// Using String#join
System.out.println(String.join(System.lineSeparator(), arr));
System.out.println();
// Using Stream
System.out.println(Arrays.stream(arr).collect(Collectors.joining(System.lineSeparator())));
}
}
Output:
line1
line2
line3
line1
line2
line3
You can use a StringBuffer
StringBuffer text = new StringBuffer();
text.append("line1");
text.append("line2");
...
useString(text.toString());
This will not append the new line character, but you can certainly append that as well for each line.
Perhaps the lowest impact method is to add a static method to append with a new line to a StringBuilder.
public static StringBuilder appendln(StringBuilder buff, String str) {
return buff.append(str).append('\n');
}
But #Joachim Sauer beats me to my preferred solution. For more complex examples you might want to use your own Writer decorator, as #Rahul G (only use private fields).
If you are not crazy about performance, I think this is clean and neat.
class DesiredStringThinger {
StringBuilder sb = new StringBuilder();
public void concat(String... s) {
for(String str : s){
sb.append(s).append("\n");
}
}
#Override
public String toString() {
return sb.toString();
}
}
In java 8 you can do this
String[] lines = new String[]{"line1", "line2", "line3"};
String s = String.join("\n", lines);
docs here