How to trim white space from all elements in array? - java

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

Related

java regular expression for String surrounded by ""

I have:
String s=" \"son of god\"\"cried out\" a good day and ok ";
This is shown on the screen as:
"son of god""cried out" a good day and ok
Pattern phrasePattern=Pattern.compile("(\".*?\")");
Matcher m=phrasePattern.matcher(s);
I want get all the phrases surrounded by "" and add them to an ArrayList<String>. It might have more than 2 such phrases. How can I get each phrase and put into my Arraylist?
With your Matcher you're 90% of the way there. You just need the #find method.
ArrayList<String> list = new ArrayList<>();
while(m.find()) {
list.add(m.group());
}
An alternative approach, and I only suggest it because you did not explicitly say you must use regex matching, is to split on ". Every other piece is your interest.
public static void main(String[] args) {
String[] testCases = new String[] {
" \"son of god\"\"cried out\" a good day and ok ",
"\"starts with a quote\" and then \"forgot the end quote",
};
for (String testCase : testCases) {
System.out.println("Input: " + testCase);
String[] pieces = testCase.split("\"");
System.out.println("Split into : " + pieces.length + " pieces");
for (int i = 0; i < pieces.length; i++) {
if (i%2 == 1) {
System.out.println(pieces[i]);
}
}
System.out.println();
}
}
Results:
Input: "son of god""cried out" a good day and ok
Split into : 5 pieces
son of god
cried out
Input: "starts with a quote" and then "forgot the end quote
Split into : 4 pieces
starts with a quote
forgot the end quote
If you want to ensure that there is an even number of double quotes, ensure the split result has an odd count.

Java array, keep getting [I#6d06d69c [duplicate]

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

Java - Simplest way to get characters that come after substring inside string

How can I get a list of characters in a string that come after a substring? Is there a built-in String method for doing this?
List<String> characters = new ArrayList<>();
String string = "Grid X: 32";
// How can I get the characters that come after "Grid X: "?
I know you could do this with a loop, but is there another way that may be simpler?
Just grab the characters after the ": "
String string = "Grid X: 32"
int indexOFColon = string.indexOf(":");
String endNumber = string.subString(indexOFColon + 2);
So you get the index of the colon, which is 6 in this case, and then grab the substring starting 2 after that, which is where your number starts.
There are two possibilities:
Use a regular expression (regex):
Matcher m = Pattern.compile("Grid X: (\\d+)");
if (m.matches(string))
{
int gridX = Integer.parseInt(m.group(1));
doSomethingWith(gridX);
}
Use the substring method of the string:
int gridX = Integer.parseInt(string.substring(string.indexOf(':')+1).trim());
doSomethingWith(gridX);
Below code can be used for getting list of chacters :-
String gridString = "Grid X: 32";
String newString = gridString.subSubString(gridString.indexOf(gridString ) + gridString .length );
char[] charArray = newString.toCharArray();
Set nodup = new HashSet();
for(char cLoop : charArray){
nodup.add(cLoop);
}
There is more than one way to get this done. The simplest is probably just substring. But it is fraught with danger if the string doesn't actually start with "Grid X: "...
String thirtyTwo = string.substring( s.indexOf("Grid X: ") + "Grid X: ".length() );
Regex is pretty good at this too.

ArrayList of Strings to one single string

I have an array list of strings (each individual element in the array list is just a word with no white space) and I want to take each element and append each next word to the end of a string.
So say the array list has
element 0 = "hello"
element 1 = "world,"
element 2 = "how"
element 3 = "are"
element 4 = "you?"
I want to make a string called sentence that contains "hello world, how are you?"
As of Java 8, this has been added to the standard Java API:
String.join() methods:
String joined = String.join("/", "2014", "10", "28" ); // "2014/10/28"
List<String> list = Arrays.asList("foo", "bar", "baz");
joined = String.join(";", list); // "foo;bar;baz"
StringJoiner is also added:
StringJoiner joiner = new StringJoiner(",");
joiner.add("foo");
joiner.add("bar");
joiner.add("baz");
String joined = joiner.toString(); // "foo,bar,baz"
Plus, it's nullsafe, which I appreciate. By this, I mean if StringJoiner encounters a null in a List, it won't throw a NPE:
#Test
public void showNullInStringJoiner() {
StringJoiner joinedErrors = new StringJoiner("|");
List<String> errorList = Arrays.asList("asdf", "bdfs", null, "das");
for (String desc : errorList) {
joinedErrors.add(desc);
}
assertEquals("asdf|bdfs|null|das", joinedErrors.toString());
}
Like suggested in the comments you can do it using StringBuilder:
StringBuilder listString = new StringBuilder();
for (String s : list)
listString.append(s).append(" ");
or without the explicit loop:
list.forEach(s -> listString.append(s).append(" "));
or even more elegant with Java 8 capabilities:
String listString = String.join(" ", list);
Use StringUtils to solve this.
e.g. Apache Commons Lang offers the join method.
StringUtils.join(myList,","))
It will iterate through your array or list of strings and will join them, using the 2nd parameter as seperator. Just remember - there is always a library for everything to make things easy.
Java 8
final String concatString= List.stream()
.collect(Collectors.joining(" "));
Well, a standard for loop should work:
String toPrint = "";
for(int i=0; i<list.size(); i++){
toPrint += list.get(i)+" ";
}
System.out.println(toPrint);
Hope that helps!
Simplest way:
String ret = "";
for (int i = 0; i < array.size(); i++) {
ret += array.get(i) + " ";
}
But if your array is long, performance of string concat is poor. You should use StringBuilder class.
this is simple method
String value = TextUtils.join(" ", sample);
sample is arraylist

String split method will not return two strings

Why does the split method not return an array with 2 elements?
for(int i = 0; i < temparray.size(); i++)
{
if (temparray.get(i).contains("_"))
System.out.println("True" + temparray.get(i).length() + " " + temparray.get(i));
String[] temp = temparray.get(i).split("_");
System.out.println(temp[0]);
//System.out.println(temp[1]);
//friendsOld.add(new Friend(temp[0],temp[1]));
}
If I uncomment either of the lines, I get ArrayOutofBoundsException: 1. The println always returns True, the length of the String, and then a String with _ located within the String - NOT at the end.
I've tried negative parameters for .split(), converting the String to char arrays and breaking the String using indexOf() to find the location of _ then splitting it manually using substring(). There might be something wrong with the String itself but here is the code for the array of Strings: ArrayList<String> temparray = new ArrayList<String>();.
It seems that you forgot the braces after the if-statement:
if (temparray.get(i).contains("_")) {
System.out.println("True" + temparray.get(i).length() + " " + temparray.get(i));
String[] temp = temparray.get(i).split("_");
System.out.println(temp[0]);
System.out.println(temp[1]);
friendsOld.add(new Friend(temp[0],temp[1]));
}
The way you wrote it, the string is splitted even when it doesn't contain an underscore. Only the output of "True [...]" is limited to strings containing one.
You should start using the debugger - it will display the values of variables when hitting an exception breakpoint allowing you to further track down the bugs in your code.
Did you mean to put all of that code in braces?
for(int i = 0; i < temparray.size(); i++)
{
if (temparray.get(i).contains("_")) {
System.out.println("True" + temparray.get(i).length() + " " + temparray.get(i));
String[] temp = temparray.get(i).split("_");
System.out.println(temp[0]);
//System.out.println(temp[1]);
//friendsOld.add(new Friend(temp[0],temp[1]));
}
}
Your if condition only applies to the next line. Therefore, if the temparray.get(i) does not contain a '_', you only get a single result from split.

Categories

Resources