String 类
字符串:就是由多个字符组成的一串数据。也可以堪称是一个字符数组。
字符串的特点:
字符串字面值“abc”也可以看成是一个字符串对象。
字符串是常量,一旦赋值不能被改变。
构造方法:
public String() //空构造
public String(byte[ ] bytes) //把字节数组转成字符串
public String(byte[ ] bytes,int offset , int length) //把字节数组的一部分转成字符串
public String(char[ ] value) //把字符数组转成字符串
public String(char[ ] value, int offset , int length) //把字符数组的一部分转成字符串
public String(String original) //把字符串常量值转成字符串
字符串的方法:
public int length() //返回字符串长度
范例:
package cn.itcast_01;
/*
*
*/
public class StringDemo {
public static void main(String[] args) {
// public String(): 空构造
String s1 = new String();
System.out.println("s1:"+s1); //结果:null
System.out.println("s1.length:"+s1.length()); //返回值 0
System.out.println("-----------------------------");
//public String(byte[] bytes) : 把字节数组转成字符串
byte[] bys = {97,98,99,100,101};
String s2 = new String(bys);
System.out.println("s2:"+s2); //结果:abcde
System.out.println("s2.length:"+s2.length()); //结果5
System.out.println("-----------------------------");
//public String (byte[] bytes,int index, int length) : 把字节数组的一部分转成字符串
//需要得到字符串bcd
byte[] bys2 = {97,98,99,100,101};
String s3 = new String(bys2,1,3);
System.out.println("s3:"+s3); //结果bcd
System.out.println("s3.length:"+s3.length()); //结果:3
System.out.println("-----------------------------");
//public String(char[] value) :把字符数组转成字符串
char[] chs = {'a','b','c','d','e','爱','吃','肉'};
String s4 = new String(chs);
System.out.println("s4:"+s4); //结果:abcde爱吃肉
System.out.println("s4.length:"+s4.length()); //结果:8
System.out.println("-------------------------------");
//public String(char[] value,int index , int length) :把字符数组的一部分转成字符串
char[] chs2 = {'a','b','c','d','e','爱','吃','肉'};
String s5 = new String(chs2,3,4);
System.out.println("s5:"+s5); //结果:de爱吃
System.out.println("s5.length:"+s5.length()); //结果:4
System.out.println("-------------------------------");
//public String(String original) :把字符串常量值转成字符串
String s6 = new String("abcde");
System.out.println("s6:"+s6); //结果:abcde
System.out.println("s6.length:"+s6.length()); //结果:5
//上面这段等价于:
String s7 = "abcde";
System.out.println("s7:"+s7); //结果:abcde
System.out.println("s7.length:"+s7.length()); //结果:5
}
}
字符串是常量,他的值在创建后不能更改。(注意:指的是值不能变,不是引用不能变)
范例:
package cn.itcast_02;
/*
* 字符串的特点:一旦赋值就不能被改变
* */
public class StringDemo {
public static void main(String[] args) {
String s = "Hello";
s +="World"; //字符串的拼接
System.out.println("s:"+s); //结果:HelloWorld
}
}
boolean equals (Object obj) :比较字符串的内容是否相同,区分大小写
boolean equalsIgnoreCase (String str) :比较字符串的内容是否相同,忽略大小写
boolean contains (String str) :判断大字符串中是否包含小字符串
boolean startsWish (String str) :判断字符串是否以某个指定的字符串开头
boolean endsWish (String str) :判断字符串是否以某个指定的字符串结尾
boolean isEmpty() : 判断字符串是否为空
范例:
package cn.itcast_02;
public class StringDemo2 {
public static void main(String[] args) {
// 创建字符串对象
String s1 = "helloworld";
String s2 = "helloworld";
String s3 = "Helloworld";
//boolean equals(Object obj):比较字符串的内容是否相同,区分大小写
System.out.println("equals:"+s1.equals(s2)); //equals:true
System.out.println("equals:"+s1.equals(s3)); //equals:false
System.out.println("----------------------");
//boolean equalsIgnoreCase(String str) : 比较字符串的内容是否相同,忽略大小写
System.out.println("equalsIgnoreCase:"+s1.equalsIgnoreCase(s2));
System.out.println("equalsIgnoreCase:"+s1.equalsIgnoreCase(s3));
System.out.println("----------------------");
//boolean contains(String str) :判断大字符串是否包含小字符串
System.out.println("contains:"+s1.contains("hello")); //contains:true
System.out.println("contains:"+s1.contains("hw")); //contains:false
// System.out.println("contains:"+s1.contains("h","w")); // 报错,只能比较单个字符串元素
System.out.println("----------------------");
//boolean startWith(String str) 判断是否以制定字符串开头
System.out.println("startWith:"+s1.startsWith("h")); //startWith:true
System.out.println("startWith:"+s1.startsWith("hello")); //startWith:true
System.out.println("----------------------");
//boolean endWith(String str) 判断是否一指定字符结尾
System.out.println("endWith:"+s1.endsWith("world")); //endWith:true
System.out.println("endWith:"+s1.endsWith("d")); //endWith:true
System.out.println("----------------------");
//boolean isEmpty() 判断字符串是否为空
System.out.println("isEmpty:"+s1.isEmpty()); //isEmpty:false
String s4 = "";
String s5 = null;
System.out.println("isEmpty:"+s4.isEmpty()); //isEmpty:true
System.out.println("isEmpty:"+s5.isEmpty()); //报错!对象不存在,不能调用方法!!!
}
}
练习01:模拟登陆账号
package cn.itcast_03;
import java.util.Scanner;
/*
* 练习:模拟登陆,给三次机会,并提示还有几次
*
* 分析:
* A 定义用户名和密码,已存在的
* B 键盘录入用户名和密码
* C 比较用户名和密码
* 如果相同,则登陆成功
* 如果有一个不同,则登陆失败
* D 给三次机会,用循环改进,最好用for循环。
*/
public class StringTest {
public static void main(String[] args) {
//定义用户名和密码。已存在的
String account = "admin";
String password = "admin";
//给三次机会,用循环改进,for循环
for (int x=0;x<3;x++) {
//x=0,1,2
//键盘输入用户名和密码
Scanner sc = new Scanner(System.in);
System.out.println("输入用户名:");
String name = sc.nextLine();
System.out.println("输入密码:");
String pwd = sc.nextLine();
//比较用户名和密码
if (name.equals(account) && pwd.equals(password)){
System.out.println("登陆成功");
break;
}
else{
//()内需要2,1,0
//如果是第0次,应该还一种提示
if((2-x)==0){
System.out.println("账号被锁定");
}
else{
System.out.println("登陆失败,你还有"+(2-x)+"次机会");
}
}
}
}
}
练习02:输入账号增强版,加入玩猜数字小游戏
class1:猜数字的类
package cn.itcast_03;
import java.util.Scanner;
/*
* 猜数字游戏的类
*/
public class GuessNumberGame {
private GuessNumberGame(){
}
public static void start(){
//产生一个随机数
int number = (int)(Math.random()*100)+1;
while(true){
//键盘录入数据
Scanner sc =new Scanner(System.in);
System.out.println("输入你要猜的数字(1-100):");
int guessNumber = sc.nextInt();
//判断
if(guessNumber>number){
System.out.println("你猜的数据"+guessNumber+"大了");
}
else if (guessNumber<number){
System.out.println("你猜的数据"+guessNumber+"小了");
}
else{
System.out.println("恭喜你猜中了");
break;
}
}
}
}
package cn.itcast_03;
import java.util.Scanner;
/*
* 练习:模拟登陆,给三次机会,并提示还有几次.如果登陆成功就可以玩猜数字小游戏
*
* 分析:
* A 定义用户名和密码,已存在的
* B 键盘录入用户名和密码
* C 比较用户名和密码
* 如果相同,则登陆成功
* 如果有一个不同,则登陆失败
* D 给三次机会,用循环改进,最好用for循环。
*/
public class StringTest2 {
public static void main(String[] args) {
//定义用户名和密码。已存在的
String account = "admin";
String password = "admin";
//给三次机会,用循环改进,for循环
for (int x=0;x<3;x++) {
//x=0,1,2
//键盘输入用户名和密码
Scanner sc = new Scanner(System.in);
System.out.println("输入用户名:");
String name = sc.nextLine();
System.out.println("输入密码:");
String pwd = sc.nextLine();
//比较用户名和密码
if (name.equals(account) && pwd.equals(password)){
System.out.println("登陆成功,开始玩猜数字游戏");
//玩猜数字游戏
GuessNumberGame.start();
break;
}
else{
//()内需要2,1,0
//如果是第0次,应该还一种提示
if((2-x)==0){
System.out.println("账号被锁定");
}
else{
System.out.println("登陆失败,你还有"+(2-x)+"次机会");
}
}
}
}
}
int length() //获取字符串长度
char charAt(int index) // 获取指定索引位置的字符
int indexOf(int ch) // 返回指定字符在此字符串中第一次出现处的索引 //int类型的原因是‘a'和97都代表’a' 都可以使用
int indexOf(String str) //返回指定字符串在此字符串中第一次出现处的索引
int indexOf(int ch.int fromIndex) //返回指定字符在此字符串中从指定位置后第一次出现处的索引
int indexOf(String str.int fromIndex) //返回指定字符串在此字符串中从指定位置后第一次出现处的索引
String substring(int start) //从指定位置开始截取字符串
String substring(int start.int end) //从指定位置开始到指定位置结束截取字符串
范例:
package cn.itcast_04;
public class StringDemo {
public static void main(String[] args) {
//定义一个字符串对象
String s = "helloworld";
//int length() :获取字符串长度
System.out.println("s.length:"+s.length());
System.out.println("---------------------");
//int indexOf(int ch) :返回指定字符在此字符串中第一次出现处的索引
System.out.println("s.index:"+s.indexOf('o'));
System.out.println("---------------------");
//int indexOf(String str) : 返回指定字符串在此字符串中第一次出现处的索引
System.out.println("s.indexOf:"+s.indexOf("wor"));
System.out.println("-----------------------");
//int indexOf(int ch,int fromIndex) 返回指定字符在此字符串中从制定位置后第一次出现处的索引
System.out.println("s.indexOf:"+s.indexOf('l', 4));
System.out.println("-----------------------");
//int indexOf(String str,int fromIndex) :返回指定字符串在此字符串中从指定位置后第一次出现处的索引。
System.out.println("s.indexOf:"+s.indexOf("rl", 4));
System.out.println("-----------------------");
//String substring(int start) :从指定位置开始截取字符串,默认到末尾
System.out.println("s.substring:"+s.substring(4));
System.out.println("-----------------------");
//String substring(int start,int end) :从指定位置开始到指定位置结束截取字符串
System.out.println("s.substring:"+s.substring(3,7));
System.out.println("s.substring:"+s.substring(3,s.length()));
}
}
练习01:遍历获取字符串中的每一个字符
方法1:使用String substring(int start,int end)方法
package cn.itcast_04;
/*
* 遍历获取字符串中的每一个字符
* 思路:
* 获取每一个字符,用String substring(int start,int end)方法
* start和end要随着循环而递增
* 使用String length可只循环数,用for
*/
public class StringTest_01 {
public static void main(String[] args) {
String s = "helloworld";
System.out.print("[");
//用for循环遍历字符串
for(int x=0;x<s.length();x++){
if (x==(s.length()-1)){
System.out.println(s.substring(s.length()-1,s.length())+"]");
}
else{
System.out.print(s.substring(x,x+1)+",");
}
}
}
}
//返回:[h,e,l,l,o,w,o,r,l,d]
方法2:使用String charAt()方法
package cn.itcast_04;
/*
* 方法2,使用String charAt()方法
*/
public class StringTest_03 {
public static void main(String[] args) {
String s = "helloworld";
for (int x=0;x<s.length();x++){
System.out.print(s.charAt(x)+",");
}
}
}
//返回h,e,l,l,o,w,o,r,l,d,
举例:“Hello123World"
package cn.itcast_04;
/*
* 统计一个字符串中大写字母字符,小写字母字符,数字字符出现的次数。(不考虑其他字符)
* 举例:"Hello123World"
*
* 思路:
* A:定义三个统计变量
* bigCount = 0
* smallCount = 0
* numberCount = 0
*
* B:遍历字符串,得到每一个字符 length() 和 charAt() 结合使用
* C:判断该字符到底属于哪种类型的。
* 大:bigCount++
* 小:smallCount++
* 数字:numberCount++
*
* 这道题目的难点是如何判断某个字符是大写,还是小写,还是数字
* 方法1:ASCII码表:
* 0——48
* A——65
* a——97
* 方法2:使用>=运算符和<=运算符,自动转换int
* char ch = s.charAt();
* if(ch>='0' && ch<='9') numberCount++
* if(ch>='a' && ch<='z') smallCount++
* if(ch>='A' && ch<='Z') bigCount++
*
*/
public class StringTest_04 {
public static void main(String[] args) {
String s = "Hello123World";
int bigCount = 0;
int smallCount = 0;
int numberCount = 0;
for (int x = 0; x < s.length(); x++) {
char ch = s.charAt(x);
if (ch >= '0' && ch <= '9') {
numberCount++;
} else if (ch >= 'a' && ch <= 'z') {
smallCount++;
} else {
bigCount++;
}
}
System.out.println("大写字母有:"+bigCount+"个");
System.out.println("小写字母有:"+smallCount+"个");
System.out.println("数字有:"+numberCount+"个");
}
}
/*结果:
大写字母有:2个
小写字母有:8个
数字有:3个*/
练习03:统计一个键盘输入的字符串中大写字母字符,小写字母字符,数字字符出现的次数。
package cn.itcast_04;
import java.util.Scanner;
/*
* 统计一个键盘录入的字符串。中大写字母字符,小写字母字符,数字字符出现的次数。
* 思路:
* A:定义三个统计变量
* bigCount = 0
* smallCount = 0
* numberCount = 0
*
* B:遍历字符串,得到每一个字符 length() 和 charAt() 结合使用
* C:判断该字符到底属于哪种类型的。
* 大:bigCount++
* 小:smallCount++
* 数字:numberCount++
*
* 这道题目的难点是如何判断某个字符是大写,还是小写,还是数字
* 方法1:ASCII码表:
* 0——48
* A——65
* a——97
* 方法2:使用>=运算符和<=运算符,自动转换int
* char ch = s.charAt();
* if(ch>='0' && ch<='9') numberCount++
* if(ch>='a' && ch<='z') smallCount++
* if(ch>='A' && ch<='Z') bigCount++
*
*/
public class StringTest_05 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("请输入字符串:");
String st = s.nextLine();
int numberCount = 0;
int smallCount = 0;
int bigCount =0;
for(int x=0;x<st.length();x++){
char ch = st.charAt(x);
if(ch>='0'&&ch<='9'){
numberCount++;
}
else if (ch>='a'&&ch<='z'){
smallCount++;
}
else if(ch>='A'&&ch<='Z')
{
bigCount++;
}
}
System.out.println("大写字母有:"+bigCount+"个");
System.out.println("小写字母有:"+smallCount+"个");
System.out.println("数字有:"+numberCount+"个");
}
}
String类的转换功能
byte[ ] getBytes() //把字符串转换成字节数组
char[ ] toCharArray() // 把字符串转换成字符数组
static String valueOf(char[ ] chs) //把字符数组转成字符串(通过静态方法)
static String valueOf(int i) // 把int类型的数据转成字符串
注意:String类的valueOf()方法可以把任意类型的数据转成字符串
String toLowerCase() //把字符串转成小写
String toUpperCase() //把字符串转成大写
String concat(String str) //把字符串拼接
范例:
package cn.itcast_05;
public class StringDemo {
public static void main(String[] args) {
//定义一个字符串对象
String s = "JavaSE";
//byte[ ] getBytes() //把字符串转换成字节数组
byte[] bys = s.getBytes();
for (int x =0;x<bys.length;x++){
System.out.println(bys[x]);
}
System.out.println("-----------------------------");
//char[ ] toCharArray() // 把字符串转换成字符数组
char[] chs=s.toCharArray();
for(int x=0;x<chs.length;x++){
System.out.println(chs[x]);
}
System.out.println("-----------------------------");
//static String valueOf(char[ ] chs) //把字符数组转成字符串(通过静态方法)
char[] ch={'J','a','v','a','S','E'};
String ss = String.valueOf(ch);
System.out.println(ss);
System.out.println("-----------------------------");
//static String valueOf(int i) // 把int类型的数据转成字符串
int i=100;
String sss=String.valueOf(i);
System.out.println(sss);
System.out.println("-----------------------------");
//String toLowerCase() //把字符串转成小写
String ssss=s.toLowerCase();
System.out.println(ssss);
System.out.println("-----------------------------");
//String toUpperCase() //把字符串转成大写
String s5=s.toUpperCase();
System.out.println(s5);
System.out.println("-----------------------------");
//String concat(String str) //把字符串拼接
String s1 = "hello";
String s2="world";
String s3=s1.concat(s2); //等价于:String s3 = s1+s2;
System.out.println(s3);
}
}
练习01:把一个字符串的首字母转成大写,其它转成小写
package cn.itcast_05; /* * 需求:把一个字符串的首字母转成大写,其余为小写。(只考虑英文大小写字幕字符) * 举例:helloWORLD * 结果:Helloworld * 思路: * A/先获取第一个字符 * B/获取除第一个字符外的字符 * C/把A转成大写 * D/把B转成小写 * E/拼接C和D */ public class StringTest_01 { public static void main(String[] args) { String s="helloWORLD"; char chA=s.charAt(0); //获取首字母 String chB=s.substring(1); //获取1号角标开始的字符串 String A=String.valueOf(chA); //将char类型的首字母转换成String类型 String A1=A.toUpperCase(); //将首字母转换成大写 String B=chB.toLowerCase(); //将1号角标后的字符串转换成小写 String AB=A1+B; //拼接 System.out.println(AB); }
String 类的其它功能}
替换功能:
String replace(char old,char new) //替换字符
String replace(String lod,String new) //替换字符串
去除字符串两端空格:
String trim()
按字典顺序比较两个字符串:
int compareTo(String str) //区分大小写
int compareToIgotrCase(String str) //不区分大小写
范例:
package cn.itcast_06; /* * String类的其他功能 */ public class StringDemo { public static void main(String[] args) { // 替换功能 String s1 = "helloworld"; String s2 = s1.replace('l', 'k'); // 替换一个字符 String s3 = s1.replace("owo", "ak47"); //替换一个字符串 System.out.println("s1:" + s1); System.out.println("s2:" + s2); System.out.println("s3:" + s3); System.out.println("------------------------"); //去除字符串两边空格 String s4=" hello world "; String s5=s4.trim(); //去除字符串两端空格 System.out.println("s4:"+s4+"---"); System.out.println("s5:"+s5+"---"); System.out.println("------------------------"); //按字典顺序比较两个字符串大小 String s6="hello"; String s7="hello"; String s8="abc"; String s9="xyz"; System.out.println(s6.compareTo(s7)); System.out.println(s6.compareTo(s8)); System.out.println(s6.compareTo(s9)); } }
String类练习
练习01:把数组中的数据按照指定格式拼接成一个字符串
举例 int[ ] arr = {1,2,3} 结果:[1,2,3]
package cn.itcast_07; /* * 把数组中的数据按照指定格式拼接成一个字符串 * 举例:int[] arr ={1,2,3} 输出结果:[1,2,3] * 思路: * 结果[1,2,3] 实际上是"[1,2,3]" 的字符串 * A/ 定义一个字符串对象,内容为空 * B/ 先吧字符串拼接一个"[" * C/ 遍历int数组,得到每一个元素 * D/ 先判断该元素是否为最后一个 * 是:就直接拼接元素和"]" * 不是:就拼接元素和逗号以及空格 * E/ 输出拼接后的字符串 */ public class StringTest_01 { public static void main(String[] args) { int[]arr={1,2,3}; //定义一个字符串对象,内容为空 String s = ""; //先拼接一个"[" s+="["; //for遍历数组,等到每一个元素 for(int x=0;x<arr.length;x++){ //判断该元素是否为最后一个 if(x==arr.length-1){ s +=arr[x]; s +="]"; } else{ s += arr[x]; s += ", "; } } System.out.println("最终的字符串:"+s); } }
练习02:字符串反转举例:键盘录入“abc" 输出结果”cba“
package cn.itcast_07; import java.util.Scanner; /* * 键盘录入"abc" 输出"cba" * 思路: * A/ 键盘录入一个字符串 * B/ 定义一个新字符串 * C/ 倒着遍历字符串,得到每一个字符 * 遍历字符串两种方式: * a/length() 和charAt()结合 * b/把字符串转成字符数组 * * D/ 把每一个字符拼接 * E/ 输出 */ public class StringTest_02 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("输入一个字符串:"); String line = sc.nextLine(); String result = ""; //定义一个新字符串 // 把字符串转成字符数组 char[] chs = line.toCharArray(); for(int x=chs.length-1;x>=0;x--){ //倒着遍历字符串,得到每一个字符 result +=chs[x]; //把每一个字符拼接 } System.out.println(result); } }
练习03:统计大串中小串出现的次数举例:在字符串”wetoghoujavaougljglewfjjavahopueejgjavaphpouopuoohjljljwejavaoseeeesejavaoueououe"
结果:java出现了5次
package cn.itcast_07; /* * 在字符串”wetoghoujavaougljglewfjjavahopueejgjavaphpouopuoohjljljwejavaoseeeesejavaoueououe" 结果:java出现了5次 思路: A/ 定义一个统计变量,初始化为0 B/ 先获取一次java在这个大串中第一次出现的索引。如果返回-1,说明不存在,返回统计变量。如果索引值不是-1,说明存在,统计变量+1 C/ 把刚辞的索引+小串的长度作为起始位置截取原始大串,得到一个新的字符串,并把该字符串重新赋值给大串 D/ 回到B即可 */ public class StringTest_03 { public static void main(String[] args) { //定义大串 String maxString ="wetoghoujavaougljglewfjjavahopueejgjavaphpouopuoohjljljwejavaoseeeesejavaoueououe"; String minString = "java"; int count = getCount(maxString,minString); System.out.println("出现的次数:"+count); } //写功能实现 /* * 两个明确: * 1.返回值类型 int * 2 参数列表:两个字符串(大小串) */ public static int getCount(String maxString,String minString){ int count = 0; //先在大串中查找一次小串第一次出现的位置 int index=maxString.indexOf(minString); while(index!=-1){ count++; //把刚才的索引+小串的长度作为开始位置截取上一次的大串,返回一个新的字符串,并把该字符串的值重新赋值个大串 int startIndex = index + minString.length(); maxString = maxString.substring(startIndex); //继续查 index = maxString.indexOf(minString); } return count; } } //返回结果:出现的次数:5