Reverse a string

Overview

In this example we will see how to reverse a string in Java. This problem is mention in Perl Weekly Challenge. Let us say we have a string ‘This is the best language in the world’. The method should return ‘world the in language best the is This‘. All the leading and trailing spaces should be removed and if there are more than one spaces between the words it should be reduced to one space. E.g. if the string is ‘ This is the best language‘, the method should return ‘language best the is This‘.

Code

In this section we will see how to solve this problem. First we will trim all the leading and trailing spaces by calling the trim() function:

str.trim()

Then we will replace more than one spaces to single space by using replaceAll():

str.trim().replaceAll(" +", " ")

Now we will convert the string into list of words by using the split() function:

str.trim().replaceAll(" +", " ").split(" ")

Now we will convert the array of string to list of strings then reverse the order:

final List<String> list = Arrays.asList(strWithSingleSpace);
Collections.reverse(list);

Now we will use the join() function to convert back to string with one space between each word:

String.join(" ", list)

Below is the full function:

public static String reverseWords(String str) {
    String[] strWithSingleSpace = str.trim().replaceAll(" +", " ").split(" ");
    final List<String> list = Arrays.asList(strWithSingleSpace);
    Collections.reverse(list);
    return String.join(" ", list);
}

Now let us see the Kotlin implementation of the same problem:

fun reverseWords(str: String): String {
    val strWithSingleSpace = str.trim { it <= ' ' }.replace(" +".toRegex(), " ").split(" ".toRegex()).toTypedArray()
    val list = Arrays.asList(*strWithSingleSpace)
    Collections.reverse(list)
    return java.lang.String.join(" ", list)
}

Conclusion

In this article we saw the step-by-step approach to reverse a given string ignoring the multiple whitespaces.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: