Reverse Any Word In 3 Minutes !
I believe that the best way to master programming or any other field is by solving problems.
In this story we are going to solve a new challenge using Java programming language, the solution is applied to any other programming language too.
The challenge is :
Write A Function, that it reverses all of the words within the string passed in.
Example:
"The best way to master programming is by solving problems " --> "problems solving by is programming master to way best the"
As Uncle Bob (Bob Martin) says :
“The Only Way to go Fast, is to go Well”.
So, for this purpose we are going to create unit tests before jumping to the solution.
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;public class ReverseWordsTest {
@Test
public void reverseTest() {
assertEquals("drinking like I",ReverseWords.reverse("I like drinking"));assertEquals(
"running like I",
ReverseWords.reverse("I like running")
);
}
To solve this problem you should follow these steps:
1- convert the string to a list of strings
2- reverse the list order
3- then join the list elements to get a string reversed
After following these steps you will get the result below in Java programming language.
import java.util.*;
public class ReverseWords{
public static String reverse(String words){
List<String> wordsAsList = Arrays.asList( words.split(" ") );
Collections.reverse( wordsAsList );
return String.join( " ", wordsAsList );
}
}
Conclusion:
From this challenge you might have learned many things on java.
Like splitting the string into an array using the string method split.
Collections.reverse to reverse a collectionand String.join to concat the elements and return the string
So, the main idea here is to focus on solving problems, then you will master automatically the tools like programming languages, frameworks,…
The video version for this story:
Share with me what do you think in comment :-)
► Recommended Books
Clean Code: A Handbook of Agile Software Craftsmanship
Head First Design Patterns: A Brain-Friendly Guide
Clean Architecture
► Computer and Monitor
New Apple MacBook Pro
Dell 27 INCH Ultrasharp U2719D Monitor
Double Arm Stand Desk Mount
USB C Hub Multiport Adapter
IDE I use for coding:
- IntelliJ
- Vscode
Those are my recommended stuff, and their are affiliate links, thanks for supporting my writing :-)