package com.Test;
public class ControlString {
public void First_toUpper(){
String S="let there be light";
//方法二
String[] s1=S.split(" "); //用空格进行分隔字符串,变成字符串数组
for(int i=0;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(){
int count=0;
String s1="peter piper picked a peck of pickled peppers";
String[] s2=s1.split(" "); //字符串中的空格来将s1分成了长度为8的字符串数组
for(int i=0;i
String s3=s2[i].substring(0,1); //截取子字符串的首位
if(s3.equals("p")){ //比较字符串是否相等
count++;
}
}
System.out.println("以p开头的单词共有"+count+"个");
}
public void Low_toUpper(){
String s="lengendary";
char[] s1=s.toCharArray();
for(int i=0;i
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);
//方法二
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();
}
}