How to join Array to String (Java)? - java

Let's assume there is an array:
String[] myArray = new String[]{"slim cat", "fat cat", "extremely fat cat"};
Now I want to transform this array into String with tokens "&", which value is:
slim cat&fat cat&extremely fat cat
How can I achieve this without using for loop? I mean the simplest solution, like we used to to in reverse way like someString.split();

Using Java 8:
String result = String.join("&", myArray);
Using Java 7 or earlier, you either need a loop or recursion.

Use guava's Joiner or java 8 StringJoiner.

Edit: Why without a for loop?
Use a StringBuilder
StringBuilder builder = new StringBuilder();
builder.append( myArray.remove(0));
for( String s : myArray) {
builder.append( "&");
builder.append( s);
}
String result = builder.toString();

You might use Arrays.toString(Object[]) and rewrite the result. Something like,
String[] myArray = { "slim cat", "fat cat", "extremely fat cat" };
String str = Arrays.toString(myArray).replace(", ", "&");
str = str.substring(1, str.length() - 1);
System.out.println(str);
Output is (as requested)
slim cat&fat cat&extremely fat cat
Note, this only works if there are no ", " in your inputs (as is the case here).

There's no way to do this job without some sort of iteration over the array. Even languages that offer some form of a join() function (which do not include Java < version 8) must internally perform some sort of iteration.
About the simplest way to do it in Java <= 7 is this:
StringBuilder sb = new StringBuilder();
String result;
for (String s : myArray) {
sb.append(s).append('&');
}
sb.deleteCharAt(sb.length() - 1);
result = sb.toString();

Please, take a look at http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#join(java.lang.Object[], char). This library is compatible with a lot of version of JDK and, as you can see, you have a lot of overridden methods.

Related

simple mathematical expression parsing

I try to write equals override function. I think I have written right but the problem is that parsing the expression. I have an array type of ArrayList<String> it takes inputs from keyboard than evaluate the result. I could compare with another ArrayList<String> variable but how can I compare the ArrayList<String> to String. For example,
String expr = "(5 + 3) * 12 / 3";
ArrayList<String> userInput = new ArrayList<>();
userInput.add("(");
userInput.add("5");
userInput.add(" ");
userInput.add("+");
userInput.add(" ");
userInput.add("3");
.
.
userInput.add("3");
userInput.add(")");
then convert userInput to String then compare using equals
As you see it is too long when a test is wanted to apply.
I have used to split but It splits combined numbers as well. like 12 to 1 and 2
public fooConstructor(String str)
{
// ArrayList<String> holdAllInputs; it is private member in class
holdAllInputs = new ArrayList<>();
String arr[] = str.split("");
for (String s : arr) {
holdAllInputs.add(s);
}
}
As you expect it doesn't give the right result. How can it be fixed? Or can someone help to writing regular expression to parse it properly as wanted?
As output I get:
(,5, ,+, ,3,), ,*, ,1,2, ,/, ,3
instead of
(,5, ,+, ,3,), ,*, ,12, ,/, ,3
The Regular Expression which helps you here is
"(?<=[-+*/()])|(?=[-+*/()])"
and of course, you need to avoid unwanted spaces.
Here we go,
String expr = "(5 + 3) * 12 / 3";
.
. // Your inputs
.
String arr[] = expr.replaceAll("\\s+", "").split("(?<=[-+*/()])|(?=[-+*/()])");
for (String s : arr)
{
System.out.println("Element : " + s);
}
Please see my expiriment : http://rextester.com/YOEQ4863
Hope it helps.
Instead of splitting the input into tokens for which you don't have a regex, it would be good to move ahead with joining the strings in the List like:
StringBuilder sb = new StringBuilder();
for (String s : userInput)
{
sb.append(s);
}
then use sb.toString() later for comparison. I would not advice String concatenation using + operator details here.
Another approach to this would be to use one of the the StringUtils.join methods in Apache Commons Lang.
import org.apache.commons.lang3.StringUtils;
String result = StringUtils.join(list, "");
If you are fortunate enough to be using Java 8, then it's even easier...just use String.join
String result = String.join("", list);
More details on this approach available here
this makes all the inputs into one string which can then be can be compared against the expression to see if it is equal
String x = "";
for(int i = 0; i < holdAllInputs.length; i++){
x = x + holdAllInputs.get(i);
}
if(expr == x){
//do something equal
}else{
//do something if not equal
}

Fill strings with 0's using formatter

I know I can fill with spaces using :
String.format("%6s", "abc"); // ___abc ( three spaces before abc
But I can't seem to find how to produce:
000abc
Edit:
I tried %06s prior to asking this. Just letting you know before more ( untried ) answers show up.
Currently I have: String.format("%6s", data ).replace(' ', '0' ) But I think there must exists a better way.
You should really consider using StringUtils from Apache Commons Lang for such String manipulation tasks as your code will get much more readable. Your example would be StringUtils.leftPad("abc", 6, ' ');
Try rolling your own static-utility method
public static String leftPadStringWithChar(String s, int fixedLength, char c){
if(fixedLength < s.length()){
throw new IllegalArgumentException();
}
StringBuilder sb = new StringBuilder(s);
for(int i = 0; i < fixedLength - s.length(); i++){
sb.insert(0, c);
}
return sb.toString();
}
And then use it, as such
System.out.println(leftPadStringWithChar("abc", 6, '0'));
OUTPUT
000abc
By all means, find a library you like for this kind of stuff and learn what's in your shiny new toolbox so you reinvent fewer wheels (that sometimes have flats). I prefer Guava to Apache Commons. In this case they are equivalent:
Strings.padStart("abc",6,'0');
Quick and dirty (set the length of the "000....00" string as the maximum len you support) :
public static String lefTpadWithZeros(String x,int minlen) {
return x.length()<minlen ?
"000000000000000".substring(0,minlen-x.length()) + x : x;
}
I think this is what you're looking for.
String.format("%06s", "abc");

Print array without brackets and commas

I'm porting a Hangman game to Android and have met a few problems. The original Java program used the console, so now I have to somehow beautify the output so that it fits my Android layout.
How do I print an array without the brackets and commas? The array contains slashes and gets replaced one-by-one when the correct letter is guessed.
I am using the usual .toString() function of the ArrayList class and my output is formatted like: [ a, n, d, r, o, i, d ]. I want it to simply print out the array as a single String.
I fill the array using this bit of code:
List<String> publicArray = new ArrayList<>();
for (int i = 0; i < secretWordLength; i++) {
hiddenArray.add(secretWord.substring(i, i + 1));
publicArray.add("-");
}
And I print it like this:
TextView currentWordView = (TextView) findViewById(R.id.CurrentWord);
currentWordView.setText(publicArray.toString());
Replace the brackets and commas with empty space.
String formattedString = myArrayList.toString()
.replace(",", "") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "") //remove the left bracket
.trim(); //remove trailing spaces from partially initialized arrays
Basically, don't use ArrayList.toString() - build the string up for yourself. For example:
StringBuilder builder = new StringBuilder();
for (String value : publicArray) {
builder.append(value);
}
String text = builder.toString();
(Personally I wouldn't call the variable publicArray when it's not actually an array, by the way.)
For Android, you can use the join method from android.text.TextUtils class like:
TextUtils.join("",array);
first
StringUtils.join(array, "");
second
Arrays.asList(arr).toString().substring(1).replaceFirst("]", "").replace(", ", "")
EDIT
probably the best one: Arrays.toString(arr)
With Java 8 or newer, you can use String.join, which provides the same functionality:
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter
String[] array = new String[] { "a", "n", "d", "r", "o", "i", "d" };
String joined = String.join("", array); //returns "android"
With an array of a different type, one should convert it to a String array or to a char sequence Iterable:
int[] numbers = { 1, 2, 3, 4, 5, 6, 7 };
//both of the following return "1234567"
String joinedNumbers = String.join("",
Arrays.stream(numbers).mapToObj(String::valueOf).toArray(n -> new String[n]));
String joinedNumbers2 = String.join("",
Arrays.stream(numbers).mapToObj(String::valueOf).collect(Collectors.toList()));
The first argument to String.join is the delimiter, and can be changed accordingly.
If you use Java8 or above, you can use with stream() with native.
publicArray.stream()
.map(Object::toString)
.collect(Collectors.joining(" "));
References
Use Java 8 Language Features
JavaDoc StringJoiner
Joining Objects into a String with Java 8 Stream API
the most simple solution for removing the brackets is,
convert the arraylist into string with .toString() method.
use String.substring(1,strLen-1).(where strLen is the length of string after conversion from arraylist).
the result string is your string with removed brackets.
I have used
Arrays.toString(array_name).replace("[","").replace("]","").replace(", ","");
as I have seen it from some of the comments above, but also i added an additional space character after the comma (the part .replace(", ","")), because while I was printing out each value in a new line, there was still the space character shifting the words. It solved my problem.
I used join() function like:
i=new Array("Hi", "Hello", "Cheers", "Greetings");
i=i.join("");
Which Prints:
HiHelloCheersGreetings
See more: Javascript Join - Use Join to Make an Array into a String in Javascript
String[] students = {"John", "Kelly", "Leah"};
System.out.println(Arrays.toString(students).replace("[", "").replace("]", " "));
//output: John, Kelly, Leah
You can use the reduce method provided for streams for Java 8 and above.Note you would have to map to string first to allow for concatenation inside of reduce operator.
publicArray.stream().map(String::valueOf).reduce((a, b) -> a + " " + b).get();
I was experimenting with ArrayList and I also wanted to remove the Square brackets after printing the Output and I found out a Solution. I just made a loop to print Array list and used the list method " myList.get(index) " , it works like a charm.
Please refer to my Code & Output below:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList mylist = new ArrayList();
Scanner scan = new Scanner(System.in);
for(int i = 0; i < 5; i++) {
System.out.println("Enter Value " + i + " to add: ");
mylist.add(scan.nextLine());
}
System.out.println("=======================");
for(int j = 0; j < 5; j++) {
System.out.print(mylist.get(j));
}
}
}
OUTPUT
Enter Value 0 to add:
1
Enter Value 1 to add:
2
Enter Value 2 to add:
3
Enter Value 3 to add:
4
Enter Value 4 to add:
5
=======================
12345
Just initialize a String object with your array
String s=new String(array);

What's the most elegant way to concatenate a list of values with delimiter in Java?

I have never found a neat(er) way of doing the following.
Say I have a list/array of strings.
abc
def
ghi
jkl
And I want to concatenate them into a single string delimited by a comma as follows:
abc,def,ghi,jkl
In Java, if I write something like this (pardon the syntax),
String[] list = new String[] {"abc","def","ghi","jkl"};
String str = null;
for (String s : list)
{
str = str + s + "," ;
}
System.out.println(str);
I'll get
abc,def,ghi,jkl, //Notice the comma in the end
So I have to rewrite the above for loop as follows
...
for (int i = 0; i < list.length; i++)
{
str = str + list[i];
if (i != list.length - 1)
{
str = str + ",";
}
}
...
Can this be done in a more elegant way in Java?
I would certainly use a StringBuilder/Buffer for efficiency, but I wanted to illustrate the case in point without being too verbose. By elegant, I mean a solution that avoids the ugly(?) if check inside the loop.
Using Guava's (formerly google-collections) joiner class:
Joiner.on(",").join(list)
Done.
Here is my version: Java Tricks: Fastest Way to Collecting Objects in a String
StringBuilder buffer = new StringBuilder ();
String delim = "";
for (Object o: list)
{
buffer.append (delim);
delim = ", "; // Avoid if(); assignment is very fast!
buffer.append (o);
}
buffer.toString ();
As an additional bonus: If your code in the loop is more complex, then this approach will produce a correct results without complex if()s.
Also note that with modern CPUs, the assignment will happen only in the cache (or probably only in a register).
Conclusion: While this code looks odd at first glance, it has many advantages.
StringBuilder builder = new StringBuilder();
for (String st: list) {
builder.append(st).append(',');
}
builder.deleteCharAt(builder.length());
String result = builder.toString();
Do not use '+' for string contacenations. It`s slow.
Look here:
http://snippets.dzone.com/posts/show/91
for a full discussion of this topic.
I'd bet that there are several classes named "StringUtil", "StringsUtil", "Strings" or anything along those lines on the classpath of any medium sized Java project. Most likely, any of them will provide a join function. Here are some examples I've found in my project:
org.apache.commons.lang.StringUtils.join(...)
org.apache.wicket.util.string.Wicket.join(...)
org.compass.core.util.StringUtils.arrayToDelimitedString(...)
As you might want to get rid of some external dependencies in the future, you may want to to something like this:
public static final MyStringUtils {
private MyStringUtils() {}
public static String join(Object[] list, String delim) {
return org.apache.commons.lang.StringUtils.join(list, delim);
}
}
Now that's what I call "elegant" ;)
check if this is useful:
List<Integer> numbers=new ArrayList<Integer>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.add(6);
String str = " ";
for(Integer s:numbers){
str=str+s+" , ";
}
System.out.println(str.substring(0,str.length()-2));
I would use a StringBuffer to implement this feature. String is immutable so everytime you concat two Strings, a new object is created.
More efficient is the use of StringBuffer:
String[] list = new String[] {"abc","def","ghi","jkl"};
StringBuffer str = new StringBuffer();
for (String s : list) {
str.append(s);
str.append(",");
}
str.deleteCharAt(str.length());
System.out.println(str); //automatically invokes StringBuffer.toString();
for (int i = 0; i < list.length-1; i++) {
str = str + list[i];
str = str + ",";
}
str = str + list[list.length-1]

Getting all the values of an array of Strings in one String

if I have,
String[] s = new String[3];
s[0] = "Ap";
s[1] = "p";
s[2] = "le";
String result = ?
If I want to get Apple out of s without looping, how do I do that?
Any short cut?
If the not looping is more important to you than preventing to import another library or if you are using apache commons lang already, anyway, you can use the StringUtils.join method
import org.apache.commons.lang.StringUtils;
String joined = StringUtils.join(s, "");
Maybe the Apache Commons have other methods that might be interesting for your project, as well. I found them to be a very useful resource for missing features in the native Java libraries.
Without looping, you can:
public String joinpart(String[] a, int i, String prefix) {
if (i < a.length) {
return joinpart(a, i + 1, prefix + a[i]);
}
return prefix;
}
then:
String[] a = new String[]{"Ap", "p", "le"};
String apple = joinpart(a, 0, "");
This is called a recursive solution.
If you know the length of your array, you can easily do the following:
String result = s[0] + s[1] +s[2];
Another option is to do the following, (which is purely academic, I would not use it in a real-world scenario as it would remove [, ], and <space> from your strings):
String result = Arrays.toString(s).replaceAll("[\\]\\[, ]", "");
Yet another option, to go along with the first attempt, but using a C-like formatter:
System.out.println(String.format("%s%s%s", s));
using Dollar is simple as typing:
String[] array = new String[] { "Ap", "p", "le" };
String result = $(array).join(); // result now is "Apple"
String result = s[0] + s[1] + s[2];
If you have an unknown number of entries, I think you'll need a loop.
Java does not have a String.join() type method. You'll have to roll one yourself if you want to hide the loop.

Categories