I have an input where a user may type in multiple words, and they are told to separate it with a space. So input may look like this:
foo
or like this:
foo bar php js
How can I check for spaces, and if there are spaces, split the words, then put it all into an array? I'll loop through that array in my program. I'm just new to string handling like this.
To split a string with space as delimiter in Java, call split() method on the string object, with space " " passed as argument to the split() method. The method returns a String Array with the splits as elements in the array.
split() method is used to split the string into various sub-strings. Then, those sub-strings are converted to an integer using the Integer. parseInt() method and store that value integer value to the Integer array.
C# allows to split a string by using multiple separators. var text = "falcon;eagle,forest,sky;cloud,water,rock;wind"; var words = text. Split(new char[] {',', ';'}); Array. ForEach(words, Console.
See explode
// Example 1 $pizza = "piece1 piece2 piece3 piece4 piece5 piece6"; $pieces = explode(" ", $pizza); echo $pieces[0]; // piece1 echo $pieces[1]; // piece2
Yes explode will do every thing for you and foreach can be used to retrieve the values from the array again. Your complete code will be something like following one:
$str = "foo bar php js"; $arr = explode(" ", $str); //print all the value which are in the array foreach($arr as $v){ echo $v; }
Hope this will help you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With