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);
Related
How can I convert int[] to comma-separated String in Java?
int[] intArray = {234, 808, 342};
Result I want:
"234, 808, 342"
Here are very similar reference question but none of those solution provide a result, exact I need.
How to convert an int array to String with toString method in Java
How do I print my Java object without getting "SomeType#2f92e0f4"?
How to convert a List<String> into a comma separated string without iterating List explicitly
What I've tried so far,
String commaSeparatedUserIds = Arrays.toString(intArray); // result: "[234, 808, 342]"
String commaSeparatedUserIds = Arrays.toString(intArray).replaceAll("\\[|\\]|,|\\s", ""); // result: "234808342"
String commaSeparatedUserIds = intArray.toString(); // garbage result
Here's a stream version which is functionally equivalent to khelwood's, yet uses different methods.
They both create an IntStream, map each int to a String and join those with commas.
They should be pretty identical in performance too, although technically I'm calling Integer.toString(int) directly whereas he's calling String.valueOf(int) which delegates to it. On the other hand I'm calling IntStream.of() which delegates to Arrays.stream(int[]), so it's a tie.
String result = IntStream.of(intArray)
.mapToObj(Integer::toString)
.collect(Collectors.joining(", "));
This should do
String arrAsStr = Arrays.toString(intArray).replaceAll("\\[|\\]", "");
After Arrays toString, replacing the [] gives you the desired output.
int[] intArray = {234, 808, 342, 564};
String s = Arrays.toString(intArray);
s = s.substring(1,s.length()-1);
This should work. basic idea is to get sub string from Arrays.toString() excluding first and last character
If want quotation in result, replace last line with:
s = "\"" + s.substring(1,s.length()-1) + "\"";
You want to convert the ints to strings, and join them with commas. You can do this with streams.
int[] intArray = {234, 808, 342};
String s = Arrays.stream(intArray)
.mapToObj(String::valueOf) // convert each int to a string
.collect(Collectors.joining(", ")); // join them with ", "
Result:
"234, 808, 342"
This is the pattern I always use for separator-joining. It's a pain to write this boilerplate every time, but it's much more efficient (in terms of both memory and processing time) than the newfangled Stream solutions that others have posted.
public static String toString(int[] arr) {
StringBuilder buf = new StringBuilder();
for (int i = 0, n = arr.length; i < n; i++) {
if (i > 0) {
buf.append(", ");
}
buf.append(arr[i]);
}
return buf.toString();
}
import java.util.Scanner;
public class CashSplitter {
public static void main(String[] args) {
Scanner S = new Scanner(System.in);
System.out.println("Cash Values");
String i = S.nextLine();
for(int b = 0;b<i.length(); b ++){
System.out.println(b);
System.out.println(i.substring(0,i.indexOf('.')+3));
i.replace(i.substring(0, i.indexOf('.') + 3), "");
System.out.println(i);
System.out.println(i.substring(0, i.indexOf('.') + 3));
}
}
}
The code should be able to take a string with multiple cash values and split them up, into individual values. For example 7.32869.32 should split out 7.32, 869.32 etc
A string is immutable, therefore replace returns a new String for you to use
try
i = i.replace(i.substring(0, i.indexOf('.') + 3), "");
Although try using
https://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html
There are several problems with your code:
You want to add two, not three, to the index of the decimal point,
You cannot use replace without assigning back to the string,
Your code assumes that there are no identical cash values.
For the last point, if you start with 2.222.222.22, you would get only one cash value instead of three, because replace would drop all three matches.
Java offers a nice way of splitting a String on a regex:
String[] parts = S.split("(?<=[.]..)")
Demo.
The regex is a look-behind that expects a dot followed by any two characters.
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
}
I have the String like:
String value = "13,14,15,16,17"
But i Dont know how many numbers are there with comma separation.
I want to compare with the variable say:
String varValue = "16"
It may be in any postion..
I want to compare these two string variables....
Please can anyone help?
You can do this sort of thing:
String values = '13,14,15,16,17'
String required = '16'
values.tokenize( ',' ).with { toks ->
println "There are ${toks.size()} elements in the list"
println "The list contains $required is ${toks.contains( required )}"
println "It is at position ${toks.indexOf( required )}"
}
Which prints
There are 5 elements in the list
The list contains 16 is true
It is at position 3
Use the split method to put the numbers in an array and then compare.
Here: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html
Do not quite understand your question.
Dont know how many numbers are there with comma separation
use String method split()
I want to compare with the variable say: String varValue = "16"
use String method contains()
You can use the split method to receive an Array. Turning the Array into a List will allow you to use some helper functions such as contains and indexOf, which can be used to return whether the token exists or the position of the token.
String value = "13,14,15,16,17";
//Checks existence
boolean contains = Arrays.asList(value.split(",")).contains("16");
//Returns position
int pos = Arrays.asList(value.split(",")).indexOf("16") + value.split(",").length + 1;
These examples all use Java.
If you are using Java , then following can be done to achieve this :
1. Split the input string into an array.
2. convert that array into a list .
Now
a) To find total elements separated by comma , Use :
size().
b) To find if the list contains required element or not , Use :
contains().
c) To find position of element in list , Use :
indexof()
So the code will look like :
import java.util.Arrays;
import java.util.List;
public class Test{
public static void main(String[] args) {
String inputString = "13,14,15,16,17";
String element = "16";
// Convert the string into array.
String values[] = inputString.split(",");
// Create a list using array elements.
List<String> valList = Arrays.asList(values);
System.out.println("Size :" + valList.size());
System.out.println("List contains 5 " + valList.contains(element));
System.out.println("Position of element" + valList.indexOf(element));
}
}
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.