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.
Related
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
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 7 years ago.
Hi I'm writing code to print all elements from an ArrayList separated by comma, the folllowing is the method I wrote. It works. But i'm wondering if it can be simplified? And is there a more elegant way to print all elements from an ArrayList separated by some delimiter? (e.g. a method that prints an ArrayList of Strings get "Tom, Sherlock, Jack")
Thanks everyone!
public String printMyArrayList() {
if(mylist.size() == 0)return "";
else if(mylist.size() == 1)return mylist.get(0).toString();
else {
String returnStr = "";
for (int i = 0; i < mylist.size() ; i++) {
if(i == 0)returnStr = mylist.get(i).toString();
else {
returnStr = returnStr + ", " + mylist.get(i).toString();
}
}
return returnStr;
}
}
Using Collectors.joining from Java 8:
return list.stream()
.map(Object::toString)
.collect(Collectors.joining(", "));
Another Java 8 solution using String.join:
List<String> l = Arrays.asList(new String[] {"foo", "bar", "baz"});
String joined = String.join(", ", l);
System.out.println(joined);
Output:
foo, bar, baz
A one-liner.
System.out.println(myArrayList.toString().replaceAll("\\[\\]", ""));
I.e. get the default String representation (which is [1, 2, 3]) and remove the braces.
Try this:
String delimiter = "";
StringBuilder sb = new StringBuilder();
for (Item x : list) {
sb.append(delimiter).append(x);
delimiter = ",";
}
You can also use the Joiner class
Joiner.on(",").join(lst)
If you're working with android try this:
android.text.TextUtils.join(", ", listOfObjects);
else there's a util in spring framework.
org.springframework.util.StringUtils.arrayToCommaDelimitedString(listOfObjects);
Use List#toString method. It will enclose with []. If you don't want to include [] than you can substring it.
String listStr= list.toString();
String withoutSym= listStr.substring(1, listStr.length()-1);
I don't know what you mean by "simple and elegant", but I'll go with it.
EDIT: String.join is probably the best way
DOUBLE EDIT: Don't use this, as pointed out in the comments below.
public String printMyArrayList(ArrayList<String> list)
{
String result = "";
for(String s : list)
{
result += s + ", ";
}
return result.substring(0, result.length()-2);
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have a helper function which finds the indexes of duplicate characters in the String.
Now whats the best way to remove these duplicates?
Thanks!
This is the best way I know to do it. It takes a string, separates it into characters, put it into a hashset (nonrepeating, ordered) and then prints (or could return the string.
This is the best way out of the ones listed
String example = "thiscode";
char[] chars = example.toCharArray();
Set<Character> str = new LinkedHashSet<Character>();
for (char c : chars) {
str.add(c);
}
StringBuilder sb = new StringBuilder();
for (Character character : str) {
sb.append(character);
}
System.out.println(sb.toString());
Alternatively:
public static String convert(String example){
char[] chars = example.toCharArray();
Set<Character> str = new LinkedHashSet<Character>();
for (char c : chars) {
str.add(c);
}
StringBuilder sb = new StringBuilder();
for (Character character : str) {
sb.append(character);
}
return sb.toString();
}
Another way to do it:
String example = "thiscode";
StringBuilder sb = new StringBuilder(example);
for (int i=0; i<example.length(); i++) //itterate throught the characters
if (!sb.toString().contains(example.charAt(i) + "")) //determine if its in the stringbuilder
sb.append(example.charAt(i)); //if not add it
example = sb.toString(); //take result
System.out.println(example);
Inefficient, but easy implementation
String example = "thiscode";
String empty = "";
boolean alphabet[] = new boolean[26];
for (char c : example.toCharArray())
if (alphabet[(int) ((c + "").toLowerCase().charAt(0) - 'a')] == false)
empty += c;
example = empty;
System.out.println(example);
Hope this helps.
You can create a set of the chracters used and utilize the add method as it returns false if the set already contains the value listed, no reason to loop over the elements more than once
String input = "somesortoftestwords";
Set<Character> charSet = new HashSet<Character>();
StringBuilder sb = new StringBuilder();
for (char c : input.toCharArray()) {
if (charSet.add(c)){
sb.append(c);
}
}
System.out.println(sb.toString());
Another Possible Solution:
Convert the String into characters
char[] charz = inputString.toCharArray();
Sort the characters
Arrays.sort(charz);
Now use a loop and check for duplicates
In the comments of one of the answers here there was talk of removing chars from a StringBuilder without the changing indexes causing problems. So I wrote this. I'm not saying this is the best way to process a String. I would used the Linked Set solution or something similar. (So don't vote down - or up for that matter :)
Here we loop for StringBuilder length -1 and check all chars AFTER that for duplicates and remove them. we only go to -1 because the last char doesn't have anything after it to check. The len - 1 calculation is done every time in the for loop, so it can't run over when chars are removed.
public String removeDuplicates(String string) {
StringBuilder stringBuilder = new StringBuilder(string);
for (int x=0;x<stringBuilder.length()-1;x++) {
String character = Character.toString(stringBuilder.charAt(x));
int i;
while ((i = stringBuilder.indexOf(character, x+1)) != -1) {
stringBuilder.replace(i, i+1, "");
}
}
return stringBuilder.toString();
}
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);
This question already has answers here:
Simple way to repeat a string
(32 answers)
Closed 4 years ago.
I did check the other questions; this question has its focus on solving this particular question the most efficient way.
Sometimes you want to create a new string with a specified length, and with a default character filling the entire string.
ie, it would be cool if you could do new String(10, '*') and create a new String from there, with a length of 10 characters all having a *.
Because such a constructor does not exist, and you cannot extend from String, you have either to create a wrapper class or a method to do this for you.
At this moment I am using this:
protected String getStringWithLengthAndFilledWithCharacter(int length, char charToFill) {
char[] array = new char[length];
int pos = 0;
while (pos < length) {
array[pos] = charToFill;
pos++;
}
return new String(array);
}
It still lacks any checking (ie, when length is 0 it will not work). I am constructing the array first because I believe it is faster than using string concatination or using a StringBuffer to do so.
Anyone else has a better sollution?
Apache Commons Lang (probably useful enough to be on the classpath of any non-trivial project) has StringUtils.repeat():
String filled = StringUtils.repeat("*", 10);
Easy!
Simply use the StringUtils class from apache commons lang project. You have a leftPad method:
StringUtils.leftPad("foobar", 10, '*'); // Returns "****foobar"
No need to do the loop, and using just standard Java library classes:
protected String getStringWithLengthAndFilledWithCharacter(int length, char charToFill) {
if (length > 0) {
char[] array = new char[length];
Arrays.fill(array, charToFill);
return new String(array);
}
return "";
}
As you can see, I also added suitable code for the length == 0 case.
Some possible solutions.
This creates a String with length-times '0' filled and replaces then the '0' with the charToFill (old school).
String s = String.format("%0" + length + "d", 0).replace('0', charToFill);
This creates a List containing length-times Strings with charToFill and then joining the List into a String.
String s = String.join("", Collections.nCopies(length, String.valueOf(charToFill)));
This creates a unlimited java8 Stream with Strings with charToFill, limits the output to length and collects the results with a String joiner (new school).
String s = Stream.generate(() -> String.valueOf(charToFill)).limit(length).collect(Collectors.joining());
In Java 11, you have repeat:
String s = " ";
s = s.repeat(1);
(Although at the time of writing still subject to change)
char[] chars = new char[10];
Arrays.fill(chars, '*');
String text = new String(chars);
To improve performance you could have a single predefined sting if you know the max length like:
String template = "####################################";
And then simply perform a substring once you know the length.
Solution using Google Guava
String filled = Strings.repeat("*", 10);
public static String fillString(int count,char c) {
StringBuilder sb = new StringBuilder( count );
for( int i=0; i<count; i++ ) {
sb.append( c );
}
return sb.toString();
}
What is wrong?
using Dollar is simple:
String filled = $("=").repeat(10).toString(); // produces "=========="
Solution using Google Guava, since I prefer it to Apache Commons-Lang:
/**
* Returns a String with exactly the given length composed entirely of
* the given character.
* #param length the length of the returned string
* #param c the character to fill the String with
*/
public static String stringOfLength(final int length, final char c)
{
return Strings.padEnd("", length, c);
}
The above is fine. Do you mind if I ask you a question - Is this causing you a problem? It seams to me you are optimizing before you know if you need to.
Now for my over engineered solution. In many (thou not all) cases you can use CharSequence instead of a String.
public class OneCharSequence implements CharSequence {
private final char value;
private final int length;
public OneCharSequence(final char value, final int length) {
this.value = value;
this.length = length;
}
public char charAt(int index) {
if(index < length) return value;
throw new IndexOutOfBoundsException();
}
public int length() {
return length;
}
public CharSequence subSequence(int start, int end) {
return new OneCharSequence(value, (end-start));
}
public String toString() {
char[] array = new char[length];
Arrays.fill(array, value);
return new String(array);
}
}
One extra note: it seems that all public ways of creating a new String instance involves necessarily the copy of whatever buffer you are working with, be it a char[], a StringBuffer or a StringBuilder. From the String javadoc (and is repeated in the respective toString methods from the other classes):
The contents of the character array are copied; subsequent modification of
the character array does not affect
the newly created string.
So you'll end up having a possibly big memory copy operation after the "fast filling" of the array. The only solution that may avoid this issue is the one from #mlk, if you can manage working directly with the proposed CharSequence implementation (what may be the case).
PS: I would post this as a comment but I don't have enough reputation to do that yet.
Try this Using the substring(int start, int end); method
String myLongString = "abcdefghij";
if (myLongString .length() >= 10)
String shortStr = myLongString.substring(0, 5)+ "...";
this will return abcde.
Mi solution :
pw = "1321";
if (pw.length() < 16){
for(int x = pw.length() ; x < 16 ; x++){
pw += "*";
}
}
The output :
1321************
Try this jobber
String stringy =null;
byte[] buffer = new byte[100000];
for (int i = 0; i < buffer.length; i++) {
buffer[i] =0;
}
stringy =StringUtils.toAsciiString(buffer);