CS 201: Data Structures

Lab: more Java practice

Nothing to hand in

Goals

Write the following programs

Having trouble? Ask questions. Want to make the program do something more interesting? Go for it. This time is for learning and practicing. You will not need to hand these programs in.

How will you test each program? Make sure you know how you'll be able to tell whether you're done with each program.

Try to team up with someone whose Java experience level is similar to yours. If you're mismatched, put the less experienced person at the keyboard and mouse.

Breaking strings into pieces

The String class's split method can be used quite simply, to split a string at commas or spaces or X's or Q's if you felt like it for some reason. Here's an example using a split on a space. Try it.

String s = "Yes, that's a hard-working rhinoceros."; String[] words = s.split(" "); for (String word : words) { System.out.println(word); }

Try it again, but add an extra space or two between some of the words in the sentence. (For example, try this with "Yes, that's a hard-working rhino.")

Want to get fancy in a totally optional not-required-for-this-course way?

Want more sophisticated string-splitting? You can also split using regular expressions, which give you powerful pattern-matching capabilities. If you want to say "split my string wherever you see a block of one or more whitespace characters," for example, you can do so like this:

String s = "Yes, that's a hard-working rhinoceros. "; String[] words = s.split("\\s+"); for (String word : words) { System.out.println(word); }

Here, \\s means "whitespace character" and + means "one or more". There are tons more

(Here's a tricky question: the regular expression documentation says that \s means a whitespace character, but I've typed \\s in my string. Why? Well, "split" expects you to send it a String containing a single backslash followed by a single s. But in Java string literals, the backslash character has a special meaning, which allows you to do things like using "\n" to indicate a newline character. To create a String that actually contains one backslash character, you have to type \\ inside the quotation marks. Thus, if you want to send \s to split, you write "\\s" which creates a String with a single backslash followed by a single s. Oof.)