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

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

Related

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

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.

Joining string array together, from certain argument, into a string? [duplicate]

This question already has answers here:
What's the best way to build a string of delimited items in Java?
(37 answers)
Closed 6 years ago.
Here is my String array containing the following:
"message" "player" "how" "are" "you"
I am wanting to join the "how" "are" "you" part of the String[] and I am currently doing the following:
String msg = "";
for (int i = 2; i < args.length; i++)
{
msg = msg + args[i] + " ";
}
Util.messagePlayer(player, msg);
So my question is, is there a better/more efficient way of doing this?
Yes, there is a better way, everytime you are iterating that array, new String objects are getting created(because Strings are immutable), however this one is a short String, so the efficiency loss is not that considerable,still try to use StringBuilder instead
StringBuilder msg = new StringBuilder();
for (int i = 2; i < args.length; i++)
{
msg.append(args[i] + " ");
}
Util.messagePlayer(player, msg.toString);
For complete details, StringBuilder vs String concatenation in toString() in Java
String objects are immutable ones in Java, hence every time you concatenate two strings, you are creating a new Object this is costly.
Instead, you can use a StringBuilder.
More about how to use it is well described here:
Correct way to use StringBuilder

Determining if a given string of words has words greater than 5 letters long

So, I'm in need of help on my homework assignment. Here's the question:
Write a static method, getBigWords, that gets a String parameter and returns an array whose elements are the words in the parameter that contain more than 5 letters. (A word is defined as a contiguous sequence of letters.) So, given a String like "There are 87,000,000 people in Canada", getBigWords would return an array of two elements, "people" and "Canada".
What I have so far:
public static getBigWords(String sentence)
{
String[] a = new String;
String[] split = sentence.split("\\s");
for(int i = 0; i < split.length; i++)
{
if(split[i].length => 5)
{
a.add(split[i]);
}
}
return a;
}
I don't want an answer, just a means to guide me in the right direction. I'm a novice at programming, so it's difficult for me to figure out what exactly I'm doing wrong.
EDIT:
I've now modified my method to:
public static String[] getBigWords(String sentence)
{
ArrayList<String> result = new ArrayList<String>();
String[] split = sentence.split("\\s+");
for(int i = 0; i < split.length; i++)
{
if(split[i].length() > 5)
{
if(split[i].matches("[a-zA-Z]+"))
{
result.add(split[i]);
}
}
}
return result.toArray(new String[0]);
}
It prints out the results I want, but the online software I use to turn in the assignment, still says I'm doing something wrong. More specifically, it states:
Edith de Stance states:
⇒     You might want to use: +=
⇒     You might want to use: ==
⇒     You might want to use: +
not really sure what that means....
The main problem is that you can't have an array that makes itself bigger as you add elements.
You have 2 options:
ArrayList (basically a variable-length array).
Make an array guaranteed to be bigger.
Also, some notes:
The definition of an array needs to look like:
int size = ...; // V- note the square brackets here
String[] a = new String[size];
Arrays don't have an add method, you need to keep track of the index yourself.
You're currently only splitting on spaces, so 87,000,000 will also match. You could validate the string manually to ensure it consists of only letters.
It's >=, not =>.
I believe the function needs to return an array:
public static String[] getBigWords(String sentence)
It actually needs to return something:
return result.toArray(new String[0]);
rather than
return null;
The "You might want to use" suggestions points to that you might have to process the array character by character.
First, try and print out all the elements in your split array. Remember, you do only want you look at words. So, examine if this is the case by printing out each element of the split array inside your for loop. (I'm suspecting you will get a false positive at the moment)
Also, you need to revisit your books on arrays in Java. You can not dynamically add elements to an array. So, you will need a different data structure to be able to use an add() method. An ArrayList of Strings would help you here.
split your string on bases of white space, it will return an array. You can check the length of each word by iterating on that array.
you can split string though this way myString.split("\\s+");
Try this...
public static String[] getBigWords(String sentence)
{
java.util.ArrayList<String> result = new java.util.ArrayList<String>();
String[] split = sentence.split("\\s+");
for(int i = 0; i < split.length; i++)
{
if(split[i].length() > 5)
{
if(split[i].matches("[a-zA-Z]+"))
{
result.add(split[i]);
}
if (split[i].matches("[a-zA-Z]+,"))
{
String temp = "";
for(int j = 0; j < split[i].length(); j++)
{
if((split[i].charAt(j))!=((char)','))
{
temp += split[i].charAt(j);
//System.out.print(split[i].charAt(j) + "|");
}
}
result.add(temp);
}
}
}
return result.toArray(new String[0]);
}
Whet you have done is correct but you can't you add method in array. You should set like a[position]= spilt[i]; if you want to ignore number then check by Float.isNumber() method.
Your logic is valid, but you have some syntax issues. If you are not using an IDE like Eclipse that shows you syntax errors, try commenting out lines to pinpoint which ones are syntactically incorrect. I want to also tell you that once an array is created its length cannot change. Hopefully that sets you off in the right directions.
Apart from syntax errors at String array declaration should be like new String[n]
and add method will not be there in Array hence you should use like
a[i] = split[i];
You need to add another condition along with length condition to check that the given word have all letters this can be done in 2 ways
first way is to use Character.isLetter() method and second way is create regular expression
to check string have only letter. google it for regular expression and use matcher to match like the below
Pattern pattern=Pattern.compile();
Matcher matcher=pattern.matcher();
Final point is use another counter (let say j=0) to store output values and increment this counter as and when you store string in the array.
a[j++] = split[i];
I would use a string tokenizer (string tokenizer class in java)
Iterate through each entry and if the string length is more than 4 (or whatever you need) add to the array you are returning.
You said no code, so... (This is like 5 lines of code)

How to Convert a vector string to simple string

I need to convert a string vector in a simple string. I do not know how to proceed.
I tried various solutions such as
for(int i=1; i < easy.length; i++){
easyPuzzle = easy[i].toString();
}
System.out.println(" " + easyPuzzle);
but this solution prints only the ith element and not the entire string vector.
Use toString in Arrays class
Arrays.toString(easy);
You keep reassign a new value to easyPuzzle when you really want to concatenate:
easyPuzzle += easy[i].toString();
If easy.length is large, it might make sense to use a StringBuilder which is more efficient at concatenating than String:
StringBuilder builder = new StringBuilder();
for(int i=1; i < easy.length; i++){
builder.append(easy[i].toString());
}
easyPuzzle = builder.toString();
Also by starting your for loop at i=1 you exclude the first item. Not sure if it is on purpose or not. If not, start at i = 0.
Alternatively, to save the pain of writing the loop yourself, you can use #Manoj's answer which replaces your code by one line.
I recommend to you use StringBuilder with append(<data>) method and then convert it to String.
StringBuilder data = new StringBuilder();
for(int i = 1; i < easy.length; i++){
data.append(easy[i].toString());
}
easyPuzzle = data.toString();
String is immutable so work with it is much more consume. When you work with String, i recommend to you use StringBuilder, is more effective and faster.
Update: #Manoj answer is very usefull.

Convert ArrayList <Characters> into a String [duplicate]

This question already has answers here:
Converting ArrayList of Characters to a String?
(12 answers)
Closed 1 year ago.
Is there a simple way of converting an ArrayList that contains only characters into a string? So say we have
ArrayList<Character> arrayListChar = new ArrayList<Character>();
arrayListChar.add(a);
arrayListChar.add(b);
arrayListChar.add(c);
So the array list contains a, b, and c. Ideally what I'd want to do is turn that into a String "abc".
Iterator<Character> it = arrayListChar.iterator();
StringBuilder sb = new StringBuilder();
while(it.hasNext()) {
sb.append(it.next());
}
System.out.println(sb.toString());
You could use Apache Common Lang's StringUtils class. It has a join() function like you find in PHP.
Then the code:
StringUtils.join(arrayListChar, "")
would generate:
abc
int size = list.size();
char[] chars = new char[size];
for (int i = 0; i < size; i++) {
if (list.size() != size) {
throw new ConcurrentModificationException();
}
chars[i] = list.get(i);
}
String s = new String(chars);
Using regex magic:
String result = list.toString().replaceAll(", |\\[|\\]", "");
Get the String representation of the list, which is
[a, b, c]
and then remove the strings "[", "]", and ", ".
You can override it's toString method and implement the String formatting therein.
Override toString method of ArrayList or the better to extend the ArrayList class so that you may use old ArrayList toString() somewhere else in the code
String s = "";
for(Character i : arrayListChar)
s += i;
EDIT - as pointed out already, you should only use code like this if the number of strings to concatenate is small.

Categories