This question already has answers here:
Java: convert List<String> to a join()d String
(23 answers)
Closed 6 years ago.
I have a collection arraylist in Java.
For example when I do:
test is the collection.
System.out.println(test.getTester());
Why do I get the result of:
[jamesbond]
I only want jamesbond but why do they give me the [ ] too?
From your question, assuming that you have ArrayList of Strings as the collection (since it's printing [jamesbond]).
When you write test.getTester(), the java calls the toString() method on the collection and it'll print elements between [ and ] with separated by comma.
You can use iterator over the collection to print the individual elements.
List<String> stringColl = Arrays.asList("jamesbond","danielocean");
// Java 8
stringColl.forEach(stringElem -> System.out.println(stringElem));
// Java 7 or below
for(String stringElem : stringColl){
System.out.println(stringElem);
}
Just remove the first and last character with substring method.
String foo = test.getTester().toString();
System.out.println(foo.substring(1, foo.length() - 1);
Note: If you try to print an array with more than one object, you will see that the brackets are always the first and last character, the elements themselves are sperated with commas.
Let a String help you with that and use the replace method...
Example:
// if your list doesnt contain any element with the chars [ or ]
String listNoBrackets = l.toString().replace("[", "").replace("]", "");
System.out.println(listNoBrackets);
// if your list contains at least 1 element with the chars [ or ]
String listWithBrackets = l.toString().substring(1, l.toString().length() - 1);
System.out.println(listWithBrackets);
Related
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 4 years ago.
Say I have an array, and I need to print out the info in that array with a certain character in between each string in the array. How would I go about this? I'll provide an example.
Print out array with info seperated by a " | " without hardcoding it
ex: yes|no|maybe etc...
public class Responses {
public static void main(String[] args)
String[] response = {"yes", "no", "maybe", "perhaps"};
The only way I could think of was hard coding it, but I am not allowed to hard code it so that in the event you take out or add something to the array, it will automatically print out that info as well
EDIT: This is not the same as simply printing an array. It is printing the array with the addition of a character between each string
Use the build-in function join:
String[] response = {"yes", "no", "maybe", "perhaps"};
System.out.println(String.join("|", response)); // yes|no|maybe|perhaps
This question already has answers here:
How to split a String by space
(17 answers)
Closed 5 years ago.
I want to take in a String and split it every time I find a space. And then store each of these pieces into an array.
Let's say I have this string:
String names = "amy bob lily harry luna james";
I also have this method declaration:
public static String[] seperateNames(String names) {
String[] newNames;
// Some code here
return newNames[];
}
What would I fill this method with so I can get something like this:
newNames = {"amy", "bob", "lily", "harry", "luna", "james"};
What I think I should do is create a for-loop and inside it have an if-statement that can check if there's space.
But I really don't know how to go about doing this.
I also think I will need to use trim() after everything is stored in an array to remove spaces before and after each name stored in the array.
Any help or advice appreciated. Thanks!
public static String[] seperateNames(String names) {
return names.split(" ");
}
To start you off on your assignment, String.split splits strings on a regular expression, this expression may be an empty string:
String[] ary = "abc".split("");
Yields the array:
(java.lang.String[]) [, a, b, c]
Getting rid of the empty 1st entry is left as an exercise for the reader :-)
Note: In Java 8, the empty first element is no longer included.
This question already has answers here:
How I can index the array starting from 1 instead of zero?
(6 answers)
Closed 5 years ago.
I want to split a string and store in an array from custom index and NOT from "0" index by default.
Eg:
String splitThis = "cat,dog";
String [] array = splitThis.split(",");
System.out.println array[0] + array[1]
Above code prints "catdog" but I want "cat" to be store in index "1" and "dog" in index "2"
PS: I am very new to Programming and this is my very first question. Please correct me in syntax/logic/whatever :)
You may just add an empty entry at index 0. Something like this
String splitThis = "cat,dog";
String spit2 = ","+splitThis;
String [] array = split2.split(",");
System.out.println (array[1]);
System.out.println (array[2]);
You should probably create an entirely new class to handle that.
This question already has answers here:
Java String split removed empty values
(5 answers)
Closed 6 years ago.
I would expect the following Java code to split a string into three items:
String csv = "1,2,";
String[] tokens = csv.split(",");
System.out.println(tokens.length);
However, I am only getting two items.
I must admit that I did not analyze this very deeply, but it seems counter-intuitive to me. Both Python and C# generate three items, as follows, in Python:
def test_split(self):
line = '1,2,'
tokens = line.split(",")
for token in tokens:
print('-' + token)
-1
-2
-
and in C#:
[Test]
public void t()
{
string s = "1,2,";
var tokens = s.Split(',');
foreach (var token in tokens)
{
Console.WriteLine("-" + token);
}
}
-1
-2
-
What am I missing?
This is Java 1.8.0_101.
Use overloaded version of the method:
tokens = line.split(",", -1)
The documentation is clear on this behavior:
This method works as if by invoking the two-argument split method with
the given expression and a limit argument of zero. Trailing empty
strings are therefore not included in the resulting array.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Printing reverse of any String without using any predefined function?
Please advise how to reverse a string without using built in methods. I want to use only string class, please advise let say there is a string "john is a boy" and print "yob a si nhoj".
This method will return the string backwards. all you have to do is iterate through the string backwards and add it to another string.
you do this using a for loop, but first check if the string has a greater lenght than 0.
Java Strings have a method "charAt(index)" which return a single character on the position of the string, where position 0 is the first character. so if you would like to reverse "Boy" you would start on letter 2, then 1, and then 0, and add them all together into a new String, resulting in "yoB".
public static String reverseString(String inString) {
String resultString = "";//This is the resulting string, it is empty but we will add things in the next for loop
if(inString.length()>0) {//Check the string for a lenght greater than 0
//here we set a number to the strings lenght-1 because we start counting at 0
//and go down to 0 and add the character at that position in the original string to the resulting one
for(int stringCharIndex=inString.length()-1;stringCharIndex>=0;stringCharIndex--) {
resultString+=inString.charAt(stringCharIndex);
}
}
//finaly return the resulting string.
return resultString;
}
You could iterate through all the characters in your string and prepend them to a StringBuffer using the insert(0, char) method. Then at the end of the iteration, your StringBuffer will be the reversed string.