70 likes | 181 Vues
Join us for exciting upcoming competitions, including the ACSL Programming Contest from February 6-9, and the USACO during the same dates. The focus for ACSL Contest #2 will be on Strings. Participants will have no time limit, so you can utilize brute force to solve problems! Essential Java String methods such as charAt, compareTo, equalsIgnoreCase, indexOf, length, substring, and more will be highlighted. Learn how to parse words from a string and sort arrays of strings by length. Prepare to put your programming skills to the test!
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);