Java学习-字符串练习

1.给出一句英文句子: "let there be light"
得到一个新的字符串,每个单词的首字母都转换为大写

知识点: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.英文绕口令
peter piper picked a peck of pickled peppers
统计这段绕口令有多少个以p开头的单词

知识点: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.间隔大小写模式

把 lengendary 改成间隔大写小写模式,即 LeNgEnDaRy

知识点: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.把 lengendary 最后一个字母变大写

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.练习-把最后一个two单词首字母大写

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     }

猜你喜欢

转载自www.cnblogs.com/gilgamesh-hjb/p/12172302.html
今日推荐