This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
I am using trying to use the toString(int[]) method, but I think I am doing it wrong:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html#toString(int[])
My code:
int[] array = new int[lnr.getLineNumber() + 1];
int i = 0;
System.out.println(array.toString());
The output is:
[I#23fc4bec
Also I tried printing like this, but:
System.out.println(new String().toString(array)); // **error on next line**
The method toString() in the type String is not applicable for the arguments (int[])
I took this code out of bigger and more complex code, but I can add it if needed. But this should give general information.
I am looking for output, like in Oracle's documentation:
The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space).
What you want is the Arrays.toString(int[]) method:
import java.util.Arrays;
int[] array = new int[lnr.getLineNumber() + 1];
int i = 0;
..
System.out.println(Arrays.toString(array));
There is a static Arrays.toString helper method for every different primitive java type; the one for int[] says this:
public static String toString(int[] a)
Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). Elements are converted to strings as by String.valueOf(int). Returns "null" if a is null.
System.out.println(array.toString());
should be:
System.out.println(Arrays.toString(array));
Very much agreed with #Patrik M, but the thing with Arrays.toString is that it includes "[" and "]" and "," in the output. So I'll simply use a regex to remove them from outout like this
String strOfInts = Arrays.toString(intArray).replaceAll("\\[|\\]|,|\\s", "");
and now you have a String which can be parsed back to java.lang.Number, for example,
long veryLongNumber = Long.parseLong(intStr);
Or you can use the java 8 streams, if you hate regex,
String strOfInts = Arrays
.stream(intArray)
.mapToObj(String::valueOf)
.reduce((a, b) -> a.concat(",").concat(b))
.get();
You can use java.util.Arrays:
String res = Arrays.toString(array);
System.out.println(res);
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The toString method on an array only prints out the memory address, which you are getting.
You have to loop though the array and print out each item by itself
for(int i : array) {
System.println(i);
}
Using the utility I describe here, you can have a more control over the string representation you get for your array.
String[] s = { "hello", "world" };
RichIterable<String> r = RichIterable.from(s);
r.mkString(); // gives "hello, world"
r.mkString(" | "); // gives "hello | world"
r.mkString("< ", ", ", " >"); // gives "< hello, world >"
This function returns a array of int in the string form like "6097321041141011026"
private String IntArrayToString(byte[] array) {
String strRet="";
for(int i : array) {
strRet+=Integer.toString(i);
}
return strRet;
}
Here's an example of going from a list of strings, to a single string, back to a list of strings.
Compiling:
$ javac test.java
$ java test
Running:
Initial list:
"abc"
"def"
"ghi"
"jkl"
"mno"
As single string:
"[abc, def, ghi, jkl, mno]"
Reconstituted list:
"abc"
"def"
"ghi"
"jkl"
"mno"
Source code:
import java.util.*;
public class test {
public static void main(String[] args) {
List<String> listOfStrings= new ArrayList<>();
listOfStrings.add("abc");
listOfStrings.add("def");
listOfStrings.add("ghi");
listOfStrings.add("jkl");
listOfStrings.add("mno");
show("\nInitial list:", listOfStrings);
String singleString = listOfStrings.toString();
show("As single string:", singleString);
List<String> reconstitutedList = Arrays.asList(
singleString.substring(0, singleString.length() - 1)
.substring(1).split("[\\s,]+"));
show("Reconstituted list:", reconstitutedList);
}
public static void show(String title, Object operand) {
System.out.println(title + "\n");
if (operand instanceof String) {
System.out.println(" \"" + operand + "\"");
} else {
for (String string : (List<String>)operand)
System.out.println(" \"" + string + "\"");
}
System.out.println("\n");
}
}
Related
How convert String s = "[[1, value one, v3], [2, value two, v3]]" to
"[[\"1\",\"value one\",\"v3\"],[\"2\",\"value two\",\"v3\"]]" for parsing since
Type typeToken = new TypeToken<ArrayList<ArrayList<String>>>() {}.getType();
List<List<Object>> list = new Gson().fromJson(s, typeToken);
throws com.google.gson.stream.MalformedJsonException: Unterminated array at...
This could work:
String s = "[[1, value one, v3], [2, value two, v3]]"
.replaceAll("([\\[,]\\s*)([^\\[\\]\\\"]+?)(\\s*[\\],])", "$1\"$2\"$3")
.replaceAll("([\\[,]\\s*)([^\\[\\]\\\"]+?)(\\s*[\\],])", "$1\"$2\"$3");
For some reason I could not get it to work from the first run - you have to run the replacement twice. Sorry for that.
This is the regex (without Java escaping of \):
\[([\d]+),\s*([\w\s]+),\s*([\w]+)\]
Details:
\[: matches [
([\d]+): first value specifically one or more digits
\s?([\w\s]+): second value a "string with spaces" \s* check if a spaces are present (zero or more).
\s?([\w]+): third value a string with no spaces, also here \s? is checking if a spaces are present.
\]: matches ]
Java test:
public class Main {
public static void main(String[] args) {
String s = "[[1, value one, v3], [2, value two, v3]]";
System.out.println("input: " + s);
String o = s.replaceAll("\\[([\\d]+),\\s*([\\w\\s]+),\\s*([\\w]+)\\]", "[\"$1\",\"$2\",\"$3\"]");
System.out.println("output: " + o);
}
}
Result:
input: [[1, value one, v3], [2, value two, v3]]
output: [["1","value one","v3"], ["2","value two","v3"]]
I need help to split string when substring is found, only on latest occurrence
Substring to search(example):123
String: 123hello123boy123guy123girl
Res: 123hello123boy123guy (result on split[0])
Ex: hello123boy
Res:hello
I'm trying with this function, but this split only on first occource.
public static String[] getSplitArray(String toSplitString, String spltiChar) {
return toSplitString.split("(?<=" + spltiChar + ")");
}
If you want to do it in single split(), this should work:
string.split("123((?!123).)*?$")
E.g.:
String s = "foo123bar123hhh123tillHere123Bang";
System.out.println(s.split("123((?!123).)*?$")[0]);
Outputs:
foo123bar123hhh123tillHere
Another approach would be, just split("123") then join the elements you required by 123 as delimiter.
Improvement on Kent's answer: this will actually give you a split array rather than a single-element array with the first part of your String:
String[] text = {
"123hello123boy123guy123girl", // 123hello123boy123guy
"hello123boy"// hello
};
for (String s: text) {
System.out.println(
Arrays.toString(
s.split("123(?=((?!123).)*?$)")
)
);
}
Output
[123hello123boy123guy, girl]
[hello, boy]
You don't need a regex for that, you can simply use String#lastIndexOf:
-> String s = "123hello123boy123guy123girl"
-> s.substring(0, s.lastIndexOf("123"));
| Expression value is: "123hello123boy123guy"
-> s.substring(s.lastIndexOf("123"));
| Expression value is: "123girl"
I want to split a string by '=' charecter. But I want it to split on first instance only. How can I do that ? Here is a JavaScript example for '_' char but it doesn't work for me
split string only on first instance of specified character
Example :
apple=fruit table price=5
When I try String.split('='); it gives
[apple],[fruit table price],[5]
But I need
[apple],[fruit table price=5]
Thanks
string.split("=", limit=2);
As String.split(java.lang.String regex, int limit) explains:
The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.
The string boo:and:foo, for example, yields the following results with these parameters:
Regex Limit Result
: 2 { "boo", "and:foo" }
: 5 { "boo", "and", "foo" }
: -2 { "boo", "and", "foo" }
o 5 { "b", "", ":and:f", "", "" }
o -2 { "b", "", ":and:f", "", "" }
o 0 { "b", "", ":and:f" }
Yes you can, just pass the integer param to the split method
String stSplit = "apple=fruit table price=5"
stSplit.split("=", 2);
Here is a java doc reference : String#split(java.lang.String, int)
As many other answers suggest the limit approach, This can be another way
You can use the indexOf method on String which will returns the first Occurance of the given character, Using that index you can get the desired output
String target = "apple=fruit table price=5" ;
int x= target.indexOf("=");
System.out.println(target.substring(x+1));
String string = "This is test string on web";
String splitData[] = string.split("\\s", 2);
Result ::
splitData[0] => This
splitData[1] => is test string
String string = "This is test string on web";
String splitData[] = string.split("\\s", 3);
Result ::
splitData[0] => This
splitData[1] => is
splitData[1] => test string on web
By default split method create n number's of arrays on the basis of given regex. But if you want to restrict number of arrays to create after a split than pass second argument as an integer argument.
This works:
public class Split
{
public static void main(String...args)
{
String a = "%abcdef&Ghijk%xyz";
String b[] = a.split("%", 2);
System.out.println("Value = "+b[1]);
}
}
String[] func(String apple){
String[] tmp = new String[2];
for(int i=0;i<apple.length;i++){
if(apple.charAt(i)=='='){
tmp[0]=apple.substring(0,i);
tmp[1]=apple.substring(i+1,apple.length);
break;
}
}
return tmp;
}
//returns string_ARRAY_!
i like writing own methods :)
I was just wondering what the best way to remove the white space from all the elements of a list would be.
For example if I had String [] array = {" String", "Tom Selleck "," Fish "}
How could I get all the elements as {"String","Tom Selleck","Fish"}
Thanks!
Try this:
String[] trimmedArray = new String[array.length];
for (int i = 0; i < array.length; i++)
trimmedArray[i] = array[i].trim();
Now trimmedArray contains the same strings as array, but without leading and trailing whitespace. Alternatively, you could write this for modifying the strings in-place in the same array:
for (int i = 0; i < array.length; i++)
array[i] = array[i].trim();
Another java 8 lambda option :
String[] array2 = Arrays.stream(array).map(String::trim).toArray(String[]::new);
And the ugly but optimized version without new array creation
Arrays.stream(array).map(String::trim).toArray(unused -> array);
Original "array" is modified.
Add commons-lang3-3.1.jar in your application build path.
Use the below code snippet to trim the String array.
String array = {" String", "Tom Selleck "," Fish "};
array = StringUtils.stripAll(array);
In Java 8, Arrays.parallelSetAll seems ready made for this purpose:
import java.util.Arrays;
Arrays.parallelSetAll(array, (i) -> array[i].trim());
This will modify the original array in place, replacing each element with the result of the lambda expression.
I know this is a really old post, but since Java 1.8 there is a nicer way to trim every String in an array.
Java 8 Lamda Expression solution:
List<String> temp = new ArrayList<>(Arrays.asList(yourArray));
temp.forEach(e -> {temp.set((temp.indexOf(e), e.trim()});
yourArray = temp.toArray(new String[temp.size()]);
with this solution you don't have to create a new Array.
Like in Óscar López's solution
You can just iterate over the elements in the array and call array[i].trim() on each element
For those (like me) who was looking for the same solution in Kotlin and were pointed to Java only - how to trim in Kotlin:
fun main(args: Array<String>) {
// array definition
val array = arrayListOf<String>(" String", "Tom Selleck "," Fish ")
println(array) // print original -> [ String, Tom Selleck , Fish ]
// remove leading and trailing spaces, result is arrayList
val sol1 = array.map { it.trim() }
println("sol1 = $sol1") // -> sol1 = [String, Tom Selleck, Fish]
// remove leading and trailing spaces, result is String
val sol2 = array.joinToString { it.trim() }
println("sol2 = $sol2") // -> sol2 = String, Tom Selleck, Fish
}
Not knowing how the OP happened to have {" String", "Tom Selleck "," Fish "} in an array in the first place (6 years ago), I thought I'd share what I ended up with.
My array is the result of using split on a string which might have extra spaces around delimiters. My solution was to address this at the point of the split. My code follows. After testing, I put splitWithTrim() in my Utils class of my project. It handles my use case; you might want to consider what sorts of strings and delimiters you might encounter if you decide to use it.
public class Test {
public static void main(String[] args) {
test(" abc def ghi jkl ", " ");
test(" abc; def ;ghi ; jkl; ", ";");
}
public static void test(String str, String splitOn) {
System.out.println("Splitting \"" + str + "\" on \"" + splitOn + "\"");
String[] parts = splitWithTrim(str, splitOn);
for (String part : parts) {
System.out.println("(" + part + ")");
}
}
public static String[] splitWithTrim(String str, String splitOn) {
if (splitOn.equals(" ")) {
return str.trim().split(" +");
} else {
return str.trim().split(" *" + splitOn + " *");
}
}
}
Output of running the test application is:
Splitting " abc def ghi jkl " on " "
(abc)
(def)
(ghi)
(jkl)
Splitting " abc; def ;ghi ; jkl; " on ";"
(abc)
(def)
(ghi)
(jkl)
String val = "hi hello prince";
String arr[] = val.split(" ");
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i]);
}
I have a string = "name";
I want to convert into a string array.
How do I do it?
Is there any java built in function? Manually I can do it but I'm searching for a java built in function.
I want an array where each character of the string will be a string.
like char 'n' will be now string "n" stored in an array.
To start you off on your assignment, String.split splits strings on a regular expression and 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.
String strName = "name";
String[] strArray = new String[] {strName};
System.out.println(strArray[0]); //prints "name"
The second line allocates a String array with the length of 1. Note that you don't need to specify a length yourself, such as:
String[] strArray = new String[1];
instead, the length is determined by the number of elements in the initalizer. Using
String[] strArray = new String[] {strName, "name1", "name2"};
creates an array with a length of 3.
I guess there is simply no need for it, as it won't get more simple than
String[] array = {"name"};
Of course if you insist, you could write:
static String[] convert(String... array) {
return array;
}
String[] array = convert("name","age","hobby");
[Edit]
If you want single-letter Strings, you can use:
String[] s = "name".split("");
Unfortunately s[0] will be empty, but after this the letters n,a,m,e will follow. If this is a problem, you can use e.g. System.arrayCopy in order to get rid of the first array entry.
Assuming you really want an array of single-character strings (not a char[] or Character[])
1. Using a regex:
public static String[] singleChars(String s) {
return s.split("(?!^)");
}
The zero width negative lookahead prevents the pattern matching at the start of the input, so you don't get a leading empty string.
2. Using Guava:
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
import com.google.common.base.Functions;
import com.google.common.collect.Lists;
import com.google.common.primitives.Chars;
// ...
public static String[] singleChars(String s) {
return
Lists.transform(Chars.asList(s.toCharArray()),
Functions.toStringFunction())
.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
In java 8, there is a method with which you can do this: toCharArray():
String k = "abcdef";
char[] x = k.toCharArray();
This results to the following array:
[a,b,c,d,e,f]
String data = "abc";
String[] arr = explode(data);
public String[] explode(String s) {
String[] arr = new String[s.length];
for(int i = 0; i < s.length; i++)
{
arr[i] = String.valueOf(s.charAt(i));
}
return arr;
}
Simply use the .toCharArray() method in Java:
String k = "abc";
char[] alpha = k.toCharArray();
This should work just fine in Java 8.
String array = array of characters ?
Or do you have a string with multiple words each of which should be an array element ?
String[] array = yourString.split(wordSeparator);
Convert it to type Char?
http://www.javadb.com/convert-string-to-character-array
You could use string.chars().mapToObj(e -> new String(new char[] {e}));, though this is quite lengthy and only works with java 8. Here are a few more methods:
string.split(""); (Has an extra whitespace character at the beginning of the array if used before Java 8)
string.split("|");
string.split("(?!^)");
Arrays.toString(string.toCharArray()).substring(1, string.length() * 3 + 1).split(", ");
The last one is just unnecessarily long, it's just for fun!
An additional method:
As was already mentioned, you could convert the original String "name" to a char array quite easily:
String originalString = "name";
char[] charArray = originalString.toCharArray();
To continue this train of thought, you could then convert the char array to a String array:
String[] stringArray = new String[charArray.length];
for (int i = 0; i < charArray.length; i++){
stringArray[i] = String.valueOf(charArray[i]);
}
At this point, your stringArray will be filled with the original values from your original string "name".
For example, now calling
System.out.println(stringArray[0]);
Will return the value "n" (as a String) in this case.
here is have convert simple string to string array using split method.
String [] stringArray="My Name is ABC".split(" ");
Output
stringArray[0]="My";
stringArray[1]="Name";
stringArray[2]="is";
stringArray[3]="ABC";
Splitting an empty string with String.split() returns a single element array containing an empty string. In most cases you'd probably prefer to get an empty array, or a null if you passed in a null, which is exactly what you get with org.apache.commons.lang3.StringUtils.split(str).
import org.apache.commons.lang3.StringUtils;
StringUtils.split(null) => null
StringUtils.split("") => []
StringUtils.split("abc def") => ["abc", "def"]
StringUtils.split("abc def") => ["abc", "def"]
StringUtils.split(" abc ") => ["abc"]
Another option is google guava Splitter.split() and Splitter.splitToList() which return an iterator and a list correspondingly. Unlike the apache version Splitter will throw an NPE on null:
import com.google.common.base.Splitter;
Splitter SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();
SPLITTER.split("a,b, c , , ,, ") => [a, b, c]
SPLITTER.split("") => []
SPLITTER.split(" ") => []
SPLITTER.split(null) => NullPointerException
If you want a list rather than an iterator then use Splitter.splitToList().
/**
* <pre>
* MyUtils.splitString2SingleAlphaArray(null, "") = null
* MyUtils.splitString2SingleAlphaArray("momdad", "") = [m,o,m,d,a,d]
* </pre>
* #param str the String to parse, may be null
* #return an array of parsed Strings, {#code null} if null String input
*/
public static String[] splitString2SingleAlphaArray(String s){
if (s == null )
return null;
char[] c = s.toCharArray();
String[] sArray = new String[c.length];
for (int i = 0; i < c.length; i++) {
sArray[i] = String.valueOf(c[i]);
}
return sArray;
}
Method String.split will generate empty 1st, you have to remove it from the array. It's boring.
Based on the title of this question, I came here wanting to convert a String into an array of substrings divided by some delimiter. I will add that answer here for others who may have the same question.
This makes an array of words by splitting the string at every space:
String str = "string to string array conversion in java";
String delimiter = " ";
String strArray[] = str.split(delimiter);
This creates the following array:
// [string, to, string, array, conversion, in, java]
Source
Tested in Java 8