StringDemo

package com.test.part04;

import java.util.Locale;

public class stringDemo {
public static void main(String[] args) {
//创建字符串
String hello="Hello";
String cha_cha="ChaCha";

//字符串子串 substring方法,可以从一个较大的字符串中提取子串
//substring(复制起始位置,不想复制的第一个位置)
String part01_hello = hello.substring(2);
String part02_hello = hello.substring(1,4);
System.out.println(part01_hello);
System.out.println(part02_hello);

//拼接字符串
String hello_cha = hello+cha_cha;
System.out.println(hello_cha);
//字符串与非字符串的值拼接,非字符串会转换为字符串
int num=18;
String num_hello = num+hello;
System.out.println(num_hello);

//join方法拼接字符串 delimiter 分隔符 elements 元素
//期望输出 s/m/l/xl
String all=String.join("/","s","m","l","xl");
System.out.println(all);

//重复输出字符串 repeat方法 Java11中提供
//String repeat_cha = "cha".repeat;

//修改字符串 hello变为help
//提取子串再拼接
hello=hello.substring(0,3)+"p";
System.out.println(hello);
//不是直接修改字符串本身而是修改字符串变量,让字符串变量指向另一字符串

//检查字符串是否相等 equals方法,返回布尔类型
String help="Help";
System.out.println(help.equals(hello));//区分大小写
System.out.println(help.equalsIgnoreCase(hello));//不区分大小写

//判断字符串是否为空两种方法长度为O或内容为空
System.out.println(hello.length());
System.out.println(hello.equals(""));
//特殊值null,表示目前没有任何对象与该变量关联
System.out.println(hello==null);
System.out.println(hello !=null&&hello!="");
hello="";//让hello为空串
System.out.println(hello.length());//空串长度为0
System.out.println(hello!=null);
System.out.println(hello==null);
//empty判空
System.out.println(hello.isEmpty());

//compare to 比较字符串 返回的是int值 按照字典顺序,1位于2之前返回负数,之后返回正数,相等返回0
int compare=part01_hello.compareTo(part02_hello);
System.out.println(compare);

//判断字符串是否以XX开头,或以XX结尾
System.out.println(cha_cha.startsWith("C"));//Java严格区分大小写
System.out.println(hello_cha.endsWith("c"));

//在字符中查找子串出现的位置
//第一个子串开始的位置
System.out.println(cha_cha.indexOf("ha"));//从位置1出现,返回值int 1
System.out.println(cha_cha.lastIndexOf("ha"));//4位置最后出现,返回值int 4
//从索引位置开始寻找子串
System.out.println(cha_cha.indexOf("ha",3));//从3位置开始寻找,出现位置为4
//字符串中不存在该子串
System.out.println(cha_cha.indexOf("el"));//原始字符串中不存在该子串,返回值为-1

//字符串长度
System.out.println(cha_cha.length());
System.out.println(cha_cha.length()==hello.length());//length()返回值为int类型,用==比较,返回布尔值

//改变字符串大小写
System.out.println(hello_cha.toUpperCase(Locale.ROOT));
}
}
posted @ 2022-03-11 12:04  青梅乌龙猹QWQ  阅读(30)  评论(1编辑  收藏  举报