06.01.2013 Views

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

Learning Processing: A Beginner's Guide to Programming Images ...

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

328 <strong>Learning</strong> <strong>Processing</strong><br />

// Splitting a String based on spaces<br />

String spaceswords = " The quick brown fox jumps over the lazy dog. " ;<br />

String[] list = split(spaceswords, " " );<br />

for (int i = 0; i < list.length; i + + ) {<br />

println(list[i] + " " + i);<br />

}<br />

Here is an example using a comma as the delimiter.<br />

// Splitting a String based on commas<br />

String commaswords = " The,quick,brown,fox,jumps,over,the,lazy,dog. " ;<br />

String[] list = split(commaswords, ‘ , ’ );<br />

for (int i = 0; i < list.length; i + + ) {<br />

println(list[i] + " " + i);<br />

}<br />

If you want <strong>to</strong> use more than one delimiter <strong>to</strong> split up a text, you must use the <strong>Processing</strong> function<br />

splitTokens( ). splitTokens( ) works identically is split( ) with one exception: any character that appears in<br />

the String qualifi es as a delimiter.<br />

// Splitting a String based on multiple delimiters<br />

String stuff = " hats & apples, cars + phones % elephants dog.<br />

" ;<br />

String[] list = splitTokens(stuff, " & , + . " );<br />

for (int i = 0; i < list.length; i + + ) {<br />

println(list[i] + " " + i);<br />

The period is set as a delimiter and therefore will<br />

}<br />

not be included in the last String in the array: “dog”.<br />

Exercise 18-4: Fill in what the above code will print in the <strong>Processing</strong> message window:<br />

hats_______________<br />

__________________<br />

__________________<br />

__________________<br />

__________________<br />

If we are splitting numbers in a String, the resulting array can be converted in<strong>to</strong> an integer array with<br />

<strong>Processing</strong> ’s int( ) function.<br />

// Calculate sum of a list of numbers in a String<br />

String numbers = " 8,67,5,309 " ;<br />

// Converting the String array <strong>to</strong> an int array<br />

int[] list = int(split(numbers, ' , ' ));<br />

int sum = 0;<br />

for (int i = 0; i < list.length; i + + ) {<br />

sum = sum + list[i];<br />

}<br />

println(sum);<br />

This period is not set as a delimeter and<br />

therefore will be included in the last<br />

String in the array: “dog.”<br />

Numbers in a String are not numbers<br />

and cannot be used in mathematical<br />

operations unless we convert them fi rst.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!