Java learning - string exercise

1. given an English sentence: "let there be light"
to get a new string, the first letter of each word converted to uppercase

Knowledge Point: split (), substring (start, end), toUpperCase (), length ()

 1 public class test {
 2     public static void main(String[] args) {
 3         String s = "let there be light";
 4         String[] s1 = s.split(" ");
 5         s = "";
 6         for (String x : s1) {
 7             x = x.substring(0, 1).toUpperCase() + x.substring(1, x.length()) + " ";
 8             s += x;
 9         }
10         s=s.trim();
11         System.out.println(s);
12     }
13 }

2. English tongue twister
peter piper picked a peck of pickled peppers
statistics this tongue twister how many words beginning with p

Knowledge Point: charAt (), spilt ()

 1 public class test {
 2     public static void main(String[] args) {
 3         String s = "peter piper picked a peck of pickled peppers";
 4         int sum=0;
 5         for(String x:s.split(" "))
 6         {
 7             if(x.charAt(0)=='p')
 8                 sum++;
 9         }
10         System.out.printf("一共%d个",sum);
11     }
12 }

3. interval capitalization mode

Lengendary into the interval uppercase lowercase mode, namely LeNgEnDaRy

Knowledge Point: toCharArray (), String.valueOf (), toUpperCase ()

 1 public static void main(String[] args) {
 2         String s = "lengendary";
 3         char []cs=s.toCharArray();
 4         s="";
 5         for(int i=0;i<cs.length;i++){
 6             if((i+1)%2!=0){
 7                 s+=String.valueOf(cs[i]).toUpperCase();//char转String可以用String.valueOf(char)
 8             }
 9             else{
10                 s+=cs[i];
11             }
12         }
13         System.out.println(s);
14     }

4. The variant lengendary last letter capitalized

1     public static void main(String[] args) {
2         String s = "lengendary";
3         s=s.substring(0,s.length()-1)+s.substring(s.length()-1,s.length()).toUpperCase();
4         System.out.println(s);
5 
6     }

5. Practice - the last two capitalized words

Nature has given us that two ears, two eyes, and but one tongue, to the end that we should hear and see more than we speak

 1     public static void main(String[] args) {
 2         String s = "Nature has given us that two ears, two eyes, and but one tongue, to the end that we should hear and see more than we speak";
 3         int last_index_of_Two = s.lastIndexOf("two");
 4 
 5         String s1 = s.substring(0, last_index_of_Two);
 6         String keyWord = s.substring(last_index_of_Two, last_index_of_Two + 1).toUpperCase();
 7         String s2 = s.substring(last_index_of_Two + 1, s.length());
 8 
 9         s = s1 + keyWord + s2;
10         System.out.println(s);
11     }

 

Guess you like

Origin www.cnblogs.com/gilgamesh-hjb/p/12172302.html