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());
Related
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
My program needs to read from a multi-lined .ini file, I've got it to the point it reads every line that start with a # and prints it. But i only want to to record the value after the = sign. here's what the file should look like:
#music=true
#Volume=100
#Full-Screen=false
#Update=true
this is what i want it to print:
true
100
false
true
this is my code i'm currently using:
#SuppressWarnings("resource")
public void getSettings() {
try {
BufferedReader br = new BufferedReader(new FileReader(new File("FileIO Plug-Ins/Game/game.ini")));
String input = "";
String output = "";
while ((input = br.readLine()) != null) {
String temp = input.trim();
temp = temp.replaceAll("#", "");
temp = temp.replaceAll("[*=]", "");
output += temp + "\n";
}
System.out.println(output);
}catch (IOException ex) {}
}
I'm not sure if replaceAll("[*=]", ""); truly means anything at all or if it's just searching for all for of those chars. Any help is appreciated!
Try following:
if (temp.startsWith("#")){
String[] splitted = temp.split("=");
output += splitted[1] + "\n";
}
Explanation:
To process lines only starting with desired character use String#startsWith method. When you have string to extract values from, String#split will split given text with character you give as method argument. So in your case, text before = character will be in array at position 0, text you want to print will be at position 1.
Also note, that if your file contains many lines starting with #, it should be wise not to concatenate strings together, but use StringBuilder / StringBuffer to add strings together.
Hope it helps.
Better use a StringBuffer instead of using += with a String as shown below. Also, avoid declaring variables inside loop. Please see how I've done it outside the loop. It's the best practice as far as I know.
StringBuffer outputBuffer = new StringBuffer();
String[] fields;
String temp;
while((input = br.readLine()) != null)
{
temp = input.trim();
if(temp.startsWith("#"))
{
fields = temp.split("=");
outputBuffer.append(fields[1] + "\n");
}
}
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 have this Java function that's supposed to convert the string s to title case. It should return a copy of s to the caller, leaving s preserved.
Currently, rv ends up as an empty string. Can anyone tell me why?
private static String titleCase(String s) {
String rv = new String();
StringTokenizer strtok = new StringTokenizer(s);
// handle the potential null error: (should really output a runtime warning here)
if(s == null) return null;
while(strtok.hasMoreTokens()) {
String word = strtok.nextToken();
String firstLetter = word.substring(0,1);
String restOfWord = word.substring(1);
rv.concat(firstLetter.toUpperCase() + restOfWord.toLowerCase());
}
return rv;
}
Strings being immutable in Java, once you have declared rv as "" (= new String()) it won't change unless you allocate a new String to it.
You can either replace the concat line by:
rv = rv.concat(firstLetter.toUpperCase() + restOfWord.toLowerCase());
Or better, use a StringBuilder instead of a String (not tested):
StringBuilder rv = new StringBuilder();
// [...]
rv.append(firstLetter.toUpperCase()).append(restOfWord.toLowerCase());
// [...]
return rv.toString();
I'd use WordUtils.capitalize or WordUtils.capitalizeFully.
I have the string "MO""RET" gets stored in items[1] array after the split command. After it get's stored I do a replaceall on this string and it replaces all the double quotes.
But I want it to be stored as MO"RET. How do i do it. In the csv file from which i process using split command Double quotes within the contents of a Text field are repeated (Example: This account is a ""large"" one"). So i want retain the one of the two quotes in the middle of string if it get's repeated and ignore the end quotes if present . How can i do it?
String items[] = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
items[1] has "MO""RET"
String recordType = items[1].replaceAll("\"","");
After this recordType has MORET I want it to have MO"RET
Don't use regex to split a CSV line. This is asking for trouble ;) Just parse it character-by-character. Here's an example:
public static List<List<String>> parseCsv(InputStream input, char separator) throws IOException {
BufferedReader reader = null;
List<List<String>> csv = new ArrayList<List<String>>();
try {
reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
for (String record; (record = reader.readLine()) != null;) {
boolean quoted = false;
StringBuilder fieldBuilder = new StringBuilder();
List<String> fields = new ArrayList<String>();
for (int i = 0; i < record.length(); i++) {
char c = record.charAt(i);
fieldBuilder.append(c);
if (c == '"') {
quoted = !quoted;
}
if ((!quoted && c == separator) || i + 1 == record.length()) {
fields.add(fieldBuilder.toString().replaceAll(separator + "$", "")
.replaceAll("^\"|\"$", "").replace("\"\"", "\"").trim());
fieldBuilder = new StringBuilder();
}
if (c == separator && i + 1 == record.length()) {
fields.add("");
}
}
csv.add(fields);
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
return csv;
}
Yes, there's little regex involved, but it only trims off ending separator and surrounding quotes of a single field.
You can however also grab any 3rd party Java CSV API.
How about:
String recordType = items[1].replaceAll( "\"\"", "\"" );
I prefer you to use replace instead of replaceAll.
replaceAll uses REGEX as the first argument.
The requirement is to replace two continues QUOTES with one QUOTE
String recordType = items[1].replace( "\"\"", "\"" );
To see the difference between replace and replaceAll , execute bellow code
recordType = items[1].replace( "$$", "$" );
recordType = items[1].replaceAll( "$$", "$" );
Here you can use the regular expression.
recordType = items[1].replaceAll( "\\B\"", "" );
recordType = recordType.replaceAll( "\"\\B", "" );
First statement replace the quotes in the beginning of the word with empty character.
Second statement replace the quotes in the end of the word with empty character.