Convert String to String[] in Java
๐คนโโ๏ธ Java String to String Array (and Back!) โ The Fun Wayโ
Ever wanted to break a string into tiny little pieces and then put it back together like a digital puzzle? Java's got you covered! Let's dive into the magical world of String.split()
and Pattern.split()
โ and then, like a good magician, we'll bring it all back with String.join()
! ๐ฉโจ
๐ฅ Breaking Strings Apart (String โ String Array)โ
1๏ธโฃ Using String.split()
โ The Easy Wayโ
Just like slicing a pizza ๐, split()
lets you divide a string into multiple pieces based on a delimiter.
String names = "alex,brian,charles,david";
String[] namesArray = names.split(","); // [alex, brian, charles, david]
Boom! You've got an array of names, ready for action. ๐
2๏ธโฃ Using Pattern.split()
โ The Regex Ninja Move ๐คบโ
If you like things fancy, you can use Pattern.split()
instead. Think of it like wielding a lightsaber instead of a butter knife. โ๏ธ
String names = "alex,brian,charles,david";
Pattern pattern = Pattern.compile(",");
String[] namesArray = pattern.split(names); // [alex, brian, charles, david]
It does the same thing but allows for more complex pattern matching. Imagine splitting a string based on multiple delimiters โ yeah, it's that powerful! ๐ช
๐งฉ Putting Strings Back Together (String Array โ String)โ
Now, let's reverse the magic trick and reassemble our strings with String.join()
!
String[] tokens = {"How", "To", "Do", "In", "Java"};
String blogName1 = String.join("", tokens); // HowToDoInJava
String blogName2 = String.join(" ", tokens); // How To Do In Java
String blogName3 = String.join("-", tokens); // How-To-Do-In-Java
Whether you like your words squished together, spaced out, or dashed up, String.join()
has your back! ๐ฅ
๐ Conclusionโ
Splitting and joining strings in Java is like playing with LEGO bricks โ break them apart and snap them back together however you like! ๐งฑ
๐ฌ Got questions? Drop them in the comments below!
Happy Coding! ๐