How to remove the last comma from the output in java? [duplicate] - java

This question already has answers here:
The simplest way to comma-delimit a list?
(30 answers)
Closed 2 years ago.
System.out.print(i+",");
I am trying to print a list of numbers using for loop and I am using the above line. But I get the output 1,2,3,. I need 1,2,3.
How can I do it?

Many ways.
Use a StringBuilder to make your string, then after the loop, if it is not empty, lop off the last character (sb.setLength(sb.length() - 1)).
Use a boolean to track if this is the first time through the loop. If yes, just print the number. If not, print a comma, then the number. Set the boolean to false after.
Use string joining:
List<String> items = List.of("Hello", "World!");
System.out.println(String.join(", ", items));

Here's what I would do... use a StringBuilder and append to it inside of the loop like this.
Once the loop is finished, your output string will be ready and you can just remove the last character (which will be the comma)
StringBuilder sb = new StringBuilder();
for () {
sb.append(i+",");
}
// remove last comma
sb.setLength(sb.length() - 1);
System.out.println(sb.toString);

Well there's standard library's method for it:
String.join(", ", s);

var buffer = new java.util.StringJoiner( "," );
for( var i = 1; i < endCriterion; ++i )
{
buffer.add( Integer.toString( i );
}
System.out.println( buffer.toString() );
For endCriterion == 3 this will print
1,2,3
to the console.
'java.util.StringJoiner' was added to the Java standard library with Java 8.

Related

If statement help (noob) [duplicate]

This question already has answers here:
What's the best way to check if a character is a vowel in Java?
(5 answers)
Closed 6 years ago.
I was trying to grab the first character from user entry, and determine it to be a vowel or not. I am very new, and have been struggling with this for a while. I am trying to add all vowels to the variable 'vowel', and not only will that obviously not work, but I feel like I am going the long way. Any help at all is vastly appreciated as I am very new to this.
entry = scanner.nextLine();
letters = entry.substring(0,1);
holder = entry.substring(1);
vowels = "A";
if (entry.substring(0,1).equals(vowels)) {
pigLatinVowel = entry + "way";
System.out.println(pigLatinVowel);
}
First, since you only want one character, don't use string methods, i.e. use entry.charAt(0) == 'A' instead of entry.substring(0,1).equals("A").
With that, you can then turn it around:
"AEIOU".indexOf(entry.charAt(0))
If the character at position 0 in the entry variable can be found, indexOf() returns the index position (zero-based), otherwise it returns -1.
So, to see if it is a vowel, do this:
if ("AEIOU".indexOf(entry.charAt(0)) != -1) {
pigLatinVowel = entry + "way";
System.out.println(pigLatinVowel);
}

How to add whichever character between every character of a premade String? [duplicate]

This question already has answers here:
Concatenating null strings in Java [duplicate]
(5 answers)
Closed 7 years ago.
How to add whichever character between every character of a premade String? (JAVA)
For example, I have the String "Hello world" and I have to add '_' between every character of the String.
Any function or useful code I can use to do it?
I have to do an algorithm that make me output "H_e_l_l_o_ _w_o_r_l_d"
This is what I have:
public String example(String s) {
String s2 = null;
for(int i = 0; i < s.length(); i++){
s2 += s.charAt(i) + (((i+1) == 0) ? " " : "-");
}
return s2;
}
My output in the main class is being:
nullH-e-l-l-o- -w-o-r-l-d-
Don't know why
This looks like a homework assignment. So, I won't directly write out all the code.
String = "hello world";
Say, there is a variable len = str.length() - 1. Instead of doing it from index 0, we will start our for loop from len - 1. The character 'd' is at index len, and the '_' will have to be inserted right before that. This can be done by setting the string to str = str.substring(0,i) + "_" + str.substring(i+1);
You will have to use a for loop that starts from len - 1 and goes on till the index reached is 0.
Now, on every single iteration, when you are inserting a character assigning str to str.substring(0,i) + "_" + str.substring(i+1); causes you to make a new string object, which is absolutely horrible style. This can be solved by using a StringBuilder.
Does that make it clear?
In the future, refrain from posting questions without having done any work. This community is there to help you with solving issues that you may have in your solutions, not write your solutions for you.

How to calculate tab length till the end of the String? [duplicate]

This question already has answers here:
Java String split removed empty values
(5 answers)
Closed 8 years ago.
I am spliting the String by tab like
String s = "1"+"\t"+2+"\t"+3+"\t"+"4";
System.out.println("length : "+ s.split("\\t").length);
In this case i get the length 4. But if i remove the last element 4 & give only blank, like
String s = "1"+"\t"+2+"\t"+3+"\t"+"";
System.out.println("Length : "+ s.split("\\t").length);
In this case i got the output 3. it means this is not calculating last tab.
In below case also, i need the length 4. This scenario i am using in my project & getting undesired result.
So please suggest me, How to calculate the entire length of tab delimited string, whether the last element is also blank.
Such as, if the case is,
String s = "1"+"\t"+2+"\t"+3+"\t"+"";
System.out.println("Length : "+ s.split("\\t").length);
then the answer should be 4 & if the case is,
String s = "1"+"\t"+2+"\t"+3+"\t"+"" + "\t"+ "";
System.out.println("Length : "+ s.split("\\t").length);
then the answer should be 5.
Please provide me the appropriate answer.
To prevent split from removing trailing empty spaces you need to use split(String regex, int limit) with negative limit value like
split("\t", -1)

How to delete only commas that appear because of Arrays.toString() [duplicate]

This question already has answers here:
What's the best way to build a string of delimited items in Java?
(37 answers)
Closed 8 years ago.
Replacing square brackets is not a problem, but the problem is with replacing commas,
replace(",", "") , because it does it with all commas in my table and i need to delete only those which appears because of Arrays.toString()
System.out.println( Arrays.toString( product ).replace("[", "").replace("]", "").replace(",", ""));
If there is no way of do that, maybe there are other ways to print my array, like string builder...etc? but i am not sure how to use it
Rather than using Arrays.toString, since you don't want the output it creates, use your own loop:
StringBuilder sb = new StringBuilder(400);
for (int i = 0; i < product.length; ++i) {
sb.append(product[i].toString());
}
String result = sb.toString();
Note I'm using toString on your product entries; there may be a more appropriate choice depending on what those are.
If you want a delimiter (other than ,, obviously), just append it to the StringBuilder as you go:
StringBuilder sb = new StringBuilder(400);
for (int i = 0; i < product.length; ++i) {
if (i > 0) {
sb.append(yourDelimiter);
}
sb.append(product[i].toString());
}
String result = sb.toString();
We dont know what your objects look like in your array, but you shouldnt use Arrays.toString if you dont like the output since its only a helper method to save you some time. Just iterate over your objects with a loop and print them.
There's a great library of apache where you can achieve your goal in one line of code:
org.apache.commons.lang.StringUtils
String delimiter = " ";
StringUtils.join(array, delimiter);

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);

Categories