Unformatted text preview:

CompSci 626.1String Processingÿ Often need to go through long string and Extract information from it Modify itÿ There are tools in the API for doing this However, you need to be able to write your own code because the tools may not meet your needs  Will also look at API later ÿ Sample problems: Extract all of the words from text (strip punctuation and spaces) Find all of the URLs in some file Look for key words: insert material there ???CompSci 626.2Simple String Processingÿ input has words separated by a single space No extraneous text to worry about Want output as an array of StringsArrayList<String> words = new ArrayList<String>();while (input.length() > 0) {int spPos = input.indexOf(””); // find boundaryif (spPos >= 0) {String word = input.substring(0, spPos); //extractwords.add(word);input = input.substring(spPos + 1); // chop off front}else {words.add(input);input = ””;}}String[] output = words.toArray(new String[0]);CompSci 626.3Simple String Processingÿ Remove all punctuation and spaces from input Want output as StringString output = ””;for (int k = 0; k < input.length(); k++) {char c = input.charAt(k); // get charif (Character.isLetter(c)) {// decideoutput += c; // built output}}CompSci 626.4Simple String Processingÿ Replace all ocurrences of “which” in input with “that” Want output as StringString output = ””;while (input.length() > 0) {int loc = input.indexOf(”which”); // find keyif (loc >= 0) {output += input.substring(0, loc) + ”that”;String word = input.substring(0, spPos); // buildinput = input.substring(loc + 1); // chop off front}else {output += input;input = ””;}} What are some flaws in this code?CompSci 626.5String Processing Using APIÿ Can use split method of String class to get an array Want output as String array Specify separator string For single space separator use:String[] output = input.split(””); split has two forms and many options, so look at the APICompSci 626.6String Processing Using APIÿ Can use Scanner with String as input Want output as String array Specify separator string For single space separator use:ArrayList<String> words = new ArrayList<String>();Scanner scan = new Scanner(input);while (scan.hasNext()) {words.add(scan.next());}String[] output = words.toArray(new String[0]); Scanner has many additional methods to process


View Full Document

Duke CPS 006 - String Processing

Download String Processing
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view String Processing and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view String Processing 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?