String Array to String [duplicate] - java

This question already has answers here:
How to convert an int array to String with toString method in Java [duplicate]
(8 answers)
Closed 9 years ago.
I am trying to take an arbitrary-length String[] and print it out to a String, preferably with field separators. Right now I have:
String[] start = {"first", "second", "third"}; //[] to convert
String cC = "";
String finish = ""; // Final String
String cC1 = "";
{
for (int i = 0; i < puts.length; i++) {
cC = puts[i] + ", ";
cC1 = (finish + cC);
finish = cC1;
}
}
But for some reason it is only returning the "second" value. How can I make it properly concatenate the values?
Also, could I simplify the code by using finish += cC? Thanks.

String[] start = {"first", "second", "third"};
String addedTogether = Arrays.toString(start);
System.out.println(addedTogether);
//prints [first, second, third]

If You want to append to a string you should use +=
e.g.
String[] start = {"first", "second", "third"};
String cc = "";
String separator = ",";
for (int i = 0; i < start.length; i++) {
cc += start[i];
//Not Add , if it is the last element.
if(i!=start.length-1){
cc+=separator;
}
}
etc.
with your way you are setting the last value to finish.

String[] start = {"first", "second", "third"}; //[] to convert
String finish = ""; // Final String
{
for (int i = 0; i < starts.length; i++) {
finish = finish + start[i] + ", ";
}
}
(If you wanted to do all this manually for some reason...)

Check out -- Java equivalents of C# String.Format() and String.Join()
That provides a string.join method, as well as some reading on useful string utility methods.

It is a very bad idea to concatenate Strings using += operator. It is always better to construct StringBuilder object and append all the values to it. And lastly call toString() on the StringBuilder object.
Take a look at this link to understand the performance hit associated with using + operator for string concatenation.
http://blog.eyallupu.com/2010/09/under-hood-of-java-strings.html
How Java do the string concatenation using "+"?

Related

How do I add commas when converting from Int [] to String? [duplicate]

This question already has answers here:
How to remove last comma and space in array? Java [duplicate]
(3 answers)
Closed 5 months ago.
Hei
I'm a beginner in Java and I have homework and I spent all day trying to figure out the solution and I couldn't. I'm so frustrated
Can someone help me?
Converting from any table in Int [] to string for eksmpel : int [] a = { 1,2,3} to String s = [1,2,3]
I didn't know how to put the comma, it always shows a trailing comma at the end or at the beginning a trailing comma as well as parentheses.
This is my code :
public class Test11 {
public static String til(int[] tabell) {
String str = "";
String na1 = "[";
String na2 = "]";
String na3 = ",";
String str3 = "";
for (int i = 0; i < tabell.length; i++) {
str += "," + tabell[i];
}
return str;
}
public static void main(String[] args) {
int[] tab = { 1, 2, 3 };
System.out.println(til(tab));
}
}
You need to handle the first iteration through your loop as a special case, because you don't want to add a comma the first time around. There's something you can use to know that you're in the first iteration...the fact that the string you're building is empty because you haven't added anything to it yet.
This makes extra good sense because if the string is empty, then it doesn't yet contain a term that you want to separate from the next term with a comma.
Here's how you do this:
String str = "";
for (int i = 0; i < tabell.length; i++) {
if (str.length() > 0)
str += ",";
str += tabell[i];
}
Use a variable to keep track of whether or not you're on the first iteration. If you are, don't put a comma before it.
boolean isFirst = true;
for (int i = 0; i < tabell.length; i++) {
if (!isFirst) {
str += ",";
}
isFirst = false;
str += tabell[i];
}

How to properly use StringBuffer#insert? [duplicate]

This question already has answers here:
How to insert a character in a string at a certain position?
(14 answers)
Closed 7 years ago.
I'm trying to use StringBuffer#insert to insert a char into different positions in a word but either I'm not using it right or I've misunderstood what it is this function actually does.
First off, I want it to add the letter 't' into different positions within "Java". I've given the part of the code I'm trying to use.
For example, the first time it's run it should print "tJava", then second time "Jtava" and so on until the loop ends after it prints "Javat". However, all I'm getting is:
tJava
ttJava
tttJava
ttttJava
If I'm using it wrong or there is an alternative way of doing this suggestions would be greatly appreciated.
String addLetter = "t";
String Word = "Java";
StringBuffer tempWord = new StringBuffer(Word);
for(int i = 0; i<Word.length(); i++) {
tempWord = tempWord.insert(i, addLetter);
System.out.println(tempWord);
}
When you call insert on StringBuffer the inserted value will be kept. For example :
StringBuffer test = new StringBuffer("test");
test.insert(1, "t");
test.insert(3, "t");
System.out.println(test);
would print ttetst.
So your re-assignment is not needed tempWord = tempWord.insert(i, "t"); if really you would want to keep the updated string.
Now if you want to display the original string with only 1 added character at the correct position, you will have to re-assign word to tempWord at each iteration.
String addLetter = "t";
String Word = "Java";
StringBuffer tempWord = new StringBuffer(Word);
for(int i = 0; i<Word.length(); i++) {
tempWord = new StringBuffer(Word);
System.out.println(tempWord.insert(i, addLetter));
}
StringBuffer and StringBuilder classes are mutable. You use a single reference and keep inserting data in it, thus you get this result.
Move the declaration and initialization of the StringBuffer inside the loop.
//removed (commented)
//StringBuffer tempWord = new StringBuffer(Word);
for(int i = 0; i<Word.length(); i++) {
//using StringBuilder rather than StringBuffer since you don't need synchronization at all
StringBuilder tempWord = new StringBuilder(Word);
tempWord = tempWord.insert(i, addLetter);
System.out.println(tempWord);
}
Let's look at the iterations:
i goes from 0 to "Java".length() = 4
i = 0 -> insert t in 0 -> Java -> t + Java
i = 1 -> insert t in 1 -> tJava -> t + t + Java
i = 2 -> insert t in 2 -> ttJava -> tt + t + Java
i = 3 -> insert t in 3 -> tttJava -> ttt + t + Java
What you want is in insert t in Java at a different index at each iteration, not at the result of the previous iteration.
Therefore you should not use the result of the previous iteration but re-assign your buffer:
for(int i = 0 ; i < word.length() ; i++) {
StringBuilder sb = new StringBuilder(word);
System.out.println(sb.insert(i, "t"));
}
If you insist on using a StringBuffer, you should reassign it to the original word for each iteration. The buffer remembers the insertion.
String addLetter = "t";
String word = "Java";
for(int i = 0; i<Word.length(); i++) {
StringBuffer tempWord = new StringBuffer(word);
tempWord.insert(i, addLetter);
System.out.println(tempWord);
}
Otherwise see Insert a character in a string at a certain position
StringBuilder is mutable and will update itself on the call to insert, and thus every loop iteration the instance is updated. To insert the value into the ORIGINAL string at each loop iteration, you should create a new object set to the original String
for(int i = 0; i<Word.length(); i++)
{
StringBuffer tempWord = new StringBuffer(Word);
System.out.println(tempWord.insert(i, addLetter));
}

String joining with delimiter not working in Android

I am trying to convert string array into string and join all values with delimiter (,) but it is adding only first two values, what is wrong in conversion code. Please see inline comments below
String[] array = new String[20];
for (int i = 0; i <= count; i++) {
Log.d(TAG, "arrayvalue : " + array[i]); //Here I will get 5 values which is exact value count, but in next converted log I will have concatenation of only first two values, what is wrong in conversion code.
// Joining:
StringBuilder buffer = new StringBuilder();
for (String each : array)
buffer.append(",").append(each);
String joined = buffer.deleteCharAt(0).toString();
Log.d("Prefs", "Converted Array to String : " + joined);
}
There is standard method for String join defined in Android SDK:
final String joined = TextUtils.join(",", array);
Use in dynamic array
String[] partno = new String[part.size()];
for(int i = 0; i < part.size(); i++){
partno[i]=part.get(i).getText().toString();
Hpartno= TextUtils.join(",",partno);
}

Queue of strings to single string [duplicate]

This question already has answers here:
A quick and easy way to join array elements with a separator (the opposite of split) in Java [duplicate]
(15 answers)
Closed 9 years ago.
I'm somewhat new to programming, so sorry if this is stupid..
I have a Queue of strings, and I want to turn into a single, space-delimited string.
For example {"a","b","c"} should become "a b c"
How would I go about doing this? (I google searched this and didn't find much :/)
I'm not sure what you mean by "Queue", but I'll assume it is an array and base my answer off of that assumption.
In order to combine them, try doing this.
String[] myStringArray = new String[]{"a", "b", "c"};
String myNewString = "";
for (int i = 0; i < myStringArray.length; i++) {
if (i != 0) {
myNewString += " " + myStringArray[i];
} else {
myNewString += myStringArray[i];
}
}
Now, the value of myNewString is equal to "a b c"
EDIT:
In order to not use an if each loop, use this instead:
String[] myStringArray = new String[]{"a", "b", "c"};
String myNewString = myStringArray[0];
for (int i = 1; i < myStringArray.length; i++) {
myNewString += " " + myStringArray[i];
}
I'd use the join method of the Apache StringUtils class (http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html).
This code might not work, I did not test it, but you should understand the logic.
//This string is your queue
String[] strings = new String[];
//This is your finished String
String string = "";
for(int i = 0; i < strings.length; i++) {
string = string + " " + strings[i];
}
String[] strings = { "a", "b", "c" };
String result = "";
for (int i = 0; i < strings.length; i++) {
result += strings[i] + ((i < strings.length - 1) ? " " : "");
}
The result is "a b c".
you can also use basic logic as below:
StringBuilder builder = new StringBuilder();
for(String inStr : arrInData) {
builder.append(inStr+" ");
}
return builder.toString();

How to print a specific amount of strings such as "_"? [duplicate]

This question already has answers here:
Simple way to repeat a string
(32 answers)
Closed 9 years ago.
I need to print a specific set of lines without manually typing them.
I want my output to be like this
"|Word_________|"
Is there a code which allows me to set my own amount of "_"?
One may use a format, which then padds (left or right) with spaces.
System.out.printf("|%-30s|%5s|%n", "Aa", "1");
System.out.printf("|%-30s|%5s|%n", "Bbbb", "222");
String s = String.format("|%-30s|%5s|%n", "Aa", "1").replace(' ', '_');
String fortyBlanks = String.format("%40s", "");
You can print a _ with:
System.out.print("_");
If you want more, do it multiple times (inefficient), or build up a string containing multiple and print it. You may want to look at StringBuilder.
No direct way. But with looping you can do
String s = "";
for (int i = 0; i < 10; i++) { // sample 10
s = s + "_";
}
System.out.println(s);
Still it is not a bestway to use + in looping. Best way is
StringBuilder b = new StringBuilder();
for (int i = 0; i < 10; i++) { //sample 10
b.append("_");
}
System.out.println(b.toString());
Use a for loop.
Here's the link to the java documnentation for a for loop: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args) {
int amountOf_ = 10;
System.out.println("|" + StringUtils.rightPad("Word", amountOf_, "_") + "|");
}
}

Categories

Resources