70 likes | 177 Views
Lynbrook Computer Science. February 2, 2009. Upcoming Competitions. ACSL Programming Feb 6-9 ACSL Written Feb 9 USACO February 6-9. ACSL Programming. Contest #2 Topic: Strings No time limit on ACSL! Brute force! Important Java String methods: charAt ( int index)
E N D
Lynbrook Computer Science February 2, 2009
Upcoming Competitions • ACSL Programming Feb 6-9 • ACSL Written Feb 9 • USACO February 6-9
ACSL Programming • Contest #2 Topic: Strings • No time limit on ACSL! Brute force! • Important Java String methods: • charAt(int index) • compareTo(String anotherString) • equals[IgnoreCase] (String anotherString) • [last]indexOf(String string) (String string, intfromIndex) • length() • substring(intbeginIndex) (intbeginIndex, endIndex) • starts/endsWith (String pre/suffix) (String pre/suffix, int offset) • toLower/Uppercase() • trim()
Parsing words from a string • String[] split(String regex) • Example: • String s = “Hello I like Java”; • String[] words = s.split(“\\w+”); • For (int i = 0; i < words.length; i++) • System.out.println(words[i]);
Problem • Given a paragraph, find the number of words that have length n
Solution • Use String.split(“\\w+”) to parse words • Find the length of each word and increment the number of words with that length • E.g. • String[] words = s.split(“\\w+”); • for (int i = 0; i < words.length; i++) • numWordsWithLength[words[i].length()]++;
Sorting an array of Strings by length • Implement Comparator interface class StringComparator implements Comparator<String> { //this method must be defined public int compare(String string1, String string2) { return string2.length() – string1.length(); } } • Sort using Arrays.sort: String[] words; StringComparator compare = new StringComparator(); Arrays.sort(words, compare);