java array remove space

java array remove space

To remove spaces from an array of strings in Java, you can use the replaceAll() method of the String class to replace all occurrences of the space character (' ') with an empty string ("").

Here is an example of how to remove spaces from an array of strings:

public class ArrayRemoveSpaceExample {

    public static void main(String[] args) {
        String[] words = {"hello", "world", "goodbye", "moon"};

        for (int i = 0; i < words.length; i++) {
            // Remove spaces from the string
            words[i] = words[i].replaceAll(" ", "");
        }

        // Print the modified array
        for (String word : words) {
            System.out.println(word);
        }
    }
}
S‮www:ecruo‬.lautturi.com

In this example, the replaceAll() method is used to remove all spaces from each element of the words array. The modified array is then printed to the console.

Note that the replaceAll() method uses regular expressions to match the pattern to be replaced, so you need to use the " " pattern to match a space character.

Alternatively, you can use the trim() method of the String class to remove leading and trailing spaces from the strings in the array:

for (int i = 0; i < words.length; i++) {
    // Remove leading and trailing spaces from the string
    words[i] = words[i].trim();
}
Created Time:2017-11-03 00:14:44  Author:lautturi