44 java常用类_6 _String案例演示
案例演示
需求:
- 已知String str = “this is a text” ;
- 将str中的单词单独获取出来
- 将str中的text替换为practice
- 在text前面插入一个easy
- 将每个单词的首字母改为大写
代码如下:
package com.wlw.common_class.string;
import java.util.Arrays;
public class Demo03 {
/*
需求:
1. 已知String str = "this is a text" ;
2. 将str中的单词单独获取出来
3. 将str中的text替换为practice
4. 在text前面插入一个easy
5. 将每个单词的首字母改为大写
*/
public static void main(String[] args) {
String str = "this is a text";
System.out.println("---------------1.将str中的单词单独获取出来----------------------");
String[] strings = str.split(" ");
for (String string : strings) {
System.out.println(string);
}
System.out.println("---------------2.将str中的text替换为practice----------------------");
String replace = str.replace("text", "practice ");
System.out.println(replace);
System.out.println("---------------3.在text前面插入一个easy----------------------");
String replace1 = str.replace("text", "easy text");
System.out.println(replace1);
System.out.println("---------------4.将每个单词的首字母改为大写----------------------");
for (int i = 0; i <strings.length ; i++) { //遍历数组
char c = strings[i].charAt(0); // 获得每一个字符串的首字符
char newC = Character.toUpperCase(c);//变大写
String newStr = newC + strings[i].substring(1);//合并字符串
System.out.println(newStr);
}
}
}
/*执行结果:
---------------1.将str中的单词单独获取出来----------------------
this
is
a
text
---------------2.将str中的text替换为practice----------------------
this is a practice
---------------3.在text前面插入一个easy----------------------
this is a easy text
---------------4.将每个单词的首字母改为大写----------------------
This
Is
A
Text
*/