How to Break a Long String
Breaking a string into parts is one of the basics of string operations. It is critical to more complex tasks like parsing data, which is used in decision-making processes. High-level programming languages, such as Ruby, Python, and Java all come with built-in string support and methods. Without knowing how to divide long strings, it's impossible to perform many more complex programming tasks.
Instructions
-
-
1
Copy the following example code into the blank text document:
"This is my string".split
This will split the variable "str" into substrings with a whitespace character as the delimiter; if no argument is given, Ruby will assume you want to split based on whitespace. You may add any character you like to split the string based on a different character. To do so, follow the same syntax as with Python.
-
2
Copy and paste the following below the previous example:
str.split(" ")
Python looks much like Ruby did, though Python handles the lack of a delimiter slightly differently --- Python will treat consecutive runs of any whitespace character as a single separator and return a list of the individual words.
-
-
3
Type the following in beneath the previous example:
str.split (" ");
Java has slightly more strict syntax than the previous two examples, but works in much the same way. Java outputs an array containing each string, split by whichever delimiter is given. Each line of Java is ended by a semi-colon, however.
-
1
Tips & Warnings
Because each of these returns an array or list, make sure you have an appropriate variable to assign them to.
References
- Photo Credit Erik Snyder/Lifesize/Getty Images