Java字符串的一些操作
package com.Test; public class ControlString { public void First_toUpper(){ /*给出一句英文句子:“let there be light” * 得到一个新的字符串,每个单词的首字母都替换成大写*/ String S="let there be light"; /*char[] c=S.toCharArray(); S.charAt(0); for(int i=0;i<c.length;i++){ if(c[i]==(char)32){ //当i为空格时,后一个字符设为大写 char A=S.charAt(i+1); c[i+1]=Character.toUpperCase(A); } } c[0]=Character.toUpperCase(S.charAt(0)); //将第一个字符设为大写 S=new String(c); System.out.println(S);*/ //方法二 String[] s1=S.split(" "); //用空格进行分隔字符串,变成字符串数组 for(int i=0;i<s1.length;i++){ String s2=s1[i].substring(0,1).toUpperCase(); //将字符串数组的子字符串的第一个进行转大写 String s3=s1[i].substring(1); //子字符串下标1开始后面的字符 s3=s2+s3; //拼接回去 System.out.print(s3+" "); //打印 } System.out.println(); } public void count_same_p(){ /*英文绕口令,统计这段绕口令中有多少个以p开头的单词*/ int count=0; String s1="peter piper picked a peck of pickled peppers"; String[] s2=s1.split(" "); //字符串中的空格来将s1分成了长度为8的字符串数组 for(int i=0;i<s2.length;i++){ String s3=s2[i].substring(0,1); //截取子字符串的首位 if(s3.equals("p")){ //比较字符串是否相等 count++; } } System.out.println("以p开头的单词共有"+count+"个"); } public void Low_toUpper(){ /*把lengendary改成间隔大小写模式,即LeNgEnDaRy*/ String s="lengendary"; char[] s1=s.toCharArray(); for(int i=0;i<s1.length;i+=2){ s1[i]=Character.toUpperCase(s1[i]); } String s2=String.valueOf(s1); //将字符数组转换成字符串 System.out.println("转换之后的字符串为:"+s2); } public void replace_last() { //将最后一个two单词首字母大写 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"; System.out.println(s); /*int a=s.lastIndexOf("two"); //找出字符串中最后一个出现two的下标 char[] s1=s.toCharArray(); //转换成字符数组 s1[a]=Character.toUpperCase(s1[a]); //将这个下标对应的字符转换成大写 s=new String(s1); //字符数组转换成字符串 System.out.println(s);*/ //方法二 String[] s1 = s.split(" "); //使用空格分隔字符串为字符数组 for (int i = s1.length - 1; i > 0; i--) { //从后往前,降低时间复杂度 if (s1[i].equals("two")) { String s2 = s1[i].substring(0,1).toUpperCase(); //将首字符转换为大写 String s3 = s1[i].substring(1); //子字符串下标1开始后面的字符 s1[i] = s2 + s3; break; } } for (String s4 : s1) { System.out.print(s4 + " "); //打印子字符串数组 } } public static void main(String[] args){ ControlString c1=new ControlString(); c1.First_toUpper(); c1.count_same_p(); c1.Low_toUpper(); c1.replace_last(); } }
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
K邻算法实现手写字体的识别,python