- Take a String, and make just the first letter capital.
Capital.java 1 public class Capital { 2 3 public static void main(String[] args) { 4 String x = "abcdefgh"; 5 6 String y = x.substring(0, 1).toUpperCase(); 7 String z = x.substring(1, x.length()); 8 System.out.println(y + z); 9 } 10 }
Abcdefgh
- See if a particular String belongs to an array (note that we haven't gotten to arrays yet. But we will).
InList.java 1 public class InList { 2 public static void main(String[] args) { 3 String[] a = { "a", "aa", "aaa" }; 4 5 String x = "asdfjeoi"; 6 boolean in = false; 7 for (int i=0; i<a.length; i++) { 8 String y = a[i]; 9 if (x.equals(y)) { 10 in = true; 11 break; 12 } 13 } 14 if (in == true) { 15 System.out.println("x is in a"); 16 } 17 else { 18 System.out.println("x is NOT in a"); 19 } 20 } 21 }
x is NOT in a
- Go through the words in a sentence and count how many letters are in each:
LetterCount.java 1 public class LetterCount { 2 public static void main(String[] args) { 3 String x = " words in a sentence "; 4 5 for (int i=0; i<x.length(); i++) { 6 7 if (x.charAt(i) == ' ') { 8 for (int j=i+1; j<x.length(); j++) { 9 if (x.charAt(j) == ' ') { 10 int length = j - i - 1; 11 String word = x.substring(i, j); 12 System.out.println(word); 13 System.out.println(length); 14 break; 15 } 16 } 17 } 18 } 19 } 20 }
words 5 in 2 a 1 sentence 8
Note the extra spaces around the word in order to make our algorithm work. We could also have written:
1 String x = "words in a sentence"; 2 x = " " + x + " ";
No comments:
Post a Comment