160 likes | 169 Views
Strings. Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in. Strings. Can view as array of chartacters Implemented as a class with its own methods Simplest operation on strings is catenating two strings String x = “Good”; String y = “Morning!”; String z = x + “ ” + y;
E N D
Strings Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in
Strings • Can view as array of chartacters • Implemented as a class with its own methods • Simplest operation on strings is catenating two strings String x = “Good”; String y = “Morning!”; String z = x + “ ” + y; String w = x + ‘ ’ + y; // also works • Possible to concatenate strings to variables of other types e.g., int, float, etc. • Internally converted to string
Methods of string class • Determining the length of a string String x = “abc”; int lengthOfx = x.length(); • Determining the character at a position String x = “abc”; char cAt2 = x.charAt(2); char first = x.charAt(0); char last = x.charAt(x.length()-1); • Case conversion String x = “Mainak”; String y = x.toUpperCase(); // y is “MAINAK” String z = x.toLowerCase(); // z is “mainak”
More on concatenation • Concatenating strings is different from concatenating characters String x = “a”; String y = “b”; String z = x + y; // z is “ab” char x1 = ‘a’; char y1 = ‘b’; char z1 = x1 + y1; // z is not “ab” • For concatenating two strings you can use the concat method also String z = “to”.concat(“get”).concat(“her”);
Extracting substrings • Can extract the substring starting at a position String x = “together”; String y = x.substring(2); // y is “gether” String z = x.substring(3); // z is “ether” String w = x.substring(0); // same as x String u = x.substring(x.length()-1); // “r” String v = x.substring(x.length()); // blank • Can extract substring between two positions String y = x.substring(0, 5); // y is “toget” String z = x.substring(5, x.length()); // “her” String w = x.substring(5, 6); // w is “h” String u = x.substring(5, 5); // u is “”
Searching in a string • Finding the first occurrence of a character or a substring within a string String x = “abracadabra”; int k = x.indexOf(‘a’); // k is 0 int p = x.indexOf(‘a’, 1); // p is 3; search // begins from pos 1 int t = x.indexOf(‘e’); // t is -1 int q = x.indexOf(“ra”); // q is 2 int s = x.indexOf(“ra”, 3); // s is 9 • Possible to find the last occurrence also int p = x.lastIndexOf(‘r’); // p is 9
Comparison of strings • Compares strings in dictionary order (also known as lexicographical order) • Returns zero if strings are equal String x = “abc”; String y = “abcd”; String z = “ab”; String w = “abd”; int p = x.compareTo(y); // p is negative int q = x.compareTo(x); // q is zero int r = x.compareTo(z); // r is positive int s = y.compareTo(w); // s is negative • This comparison is case sensitive • Use compareToIgnoreCase otherwise
Some more useful methods • Removing leading and trailing whitespaces String x = “ abc ”; String y = x.trim(); // y is “abc” • Test for prefix String x = “Mainak”; boolean y = x.startsWith(“Main”); // y is true boolean z = x.startsWith(“nak”, 3); // z is true • Test for suffix String x = “Canada”; boolean y = x.endsWith(“ada”); // y is true
Some more useful methods • Substitute all occurrences of a character with another character String x = “deer”; String y = x.replace(‘e’, ‘o’); // y is “door” String z = x.replace(‘a’, ‘o’); // z is “deer” • Partial string match String x = “abracadabra”; boolean y = x.regionMatches(true, 2, “bracket”, 1, 3); // y is true • The first argument should be set to true if the match is intended to be case ignorant
Converting string to integer class StringToInt { public static void main (String arg[]) { // Assume arg[0] is the input string int result = 0, pos; int len = arg[0].length(); char c; for (pos = 0; pos < len; pos++) { c = arg[0].charAt(len-pos-1); if ((c >= ‘0’) && (c <= ‘9’)) { result += ((c-’0’)*Math.pow(10, pos)); } // continued in next slide
Converting string to integer else if ((c==‘-’) && (pos==len-1)) { result = -result; } else { System.out.println(“Invalid input: ” + arg[0]); break; } } // end for if (pos==len) { System.out.println(“Integer value: ” + result); } } }
Reversing a string class StringReverse { public static void main (String arg[]) { // Assume that the input is arg[0] String reversed = “”; int pos; for (pos=arg[0].length()-1; pos >= 0; pos--) { reversed += arg[0].charAt(pos); } System.out.println (“Original: ” + arg[0] + “, Reversed: ” + reversed); } }
Sorting a list of names class NaiveDictionarySort { public static void main (String arg[]) { // Assume that the names are in arg int n = arg.length; // list size String sortedList[] = new String[n]; boolean indexArray[] = new boolean[n]; int k, j, runningIndex=0, minIndex; for (k=0; k<n; k++) { indexArray[k] = false; } // continued on next slide
Sorting a list of names while (runningIndex < n) { for (k=0; k<n; k++) { if (!indexArray[k]) break; } sortedList[runningIndex] = arg[k]; minIndex = k; for (j=k+1; j<n; j++) { if (indexArray[j]) continue; if (sortedList[runningIndex].compareTo(arg[j]) > 0) { sortedList[runningIndex] = arg[j]; minIndex = j; } } // continued on next slide
Sorting a list of names indexArray[minIndex] = true; runningIndex++; } System.out.println (“Sorted list:”); for (k=0; k<n; k++) { System.out.println (sortedList[k]); } } }
Announcement • Batches B9 and B10 will go for lab08 this Sunday 1000-1300 • No class this Sunday • This is not a Wednesday compensation