Java-String类
1.String类
1.1何为字符串:
简单理解,用一根签字将若干个字符串穿起来是串叫字符串
由多个字符串组成的一串数据叫做字符串,也可以看做字符数组
String:API解释
- Java程序中的所有字符串文字(例如"abc")都被实现为此类的实例。
- 字符串不变,他的值在创建后不能被更改
- 应为String对象是不可改变的,他们可以被共享,
字符串缓冲区支持可变字符串--integer
public static void main(String[] args) {
String s = "abc";
s = "qwe";
System.out.println(s);
}
}
1.2 String类的构造方法
- public String():
初始化新创建的String对象,以使其表示空字符串序列
- public String(byte[] bytes):通过使用平台的默认字符集解码指定的字节数组来构造新的String新的String的长度是字符集的函数,因此可能不等于字节数组的长度
- public String(byte[] bytes,int offset,int length):
例 ;String s = new String(bytes 1,3)
将字节数组的一部分转成字符串从下标索引1开始截取,截取3个元素形成一个字符串
- public String(char[] value):public String(char[] value)分配一个新的String,以便它表示当前包含在字符数组参数中的字符序列。字符数组的内容被复制;字符数组的后续修改不会影响新创建的字符串。
- public String(char[] value,int offset,int count): 例:String a = new String(chars 2,4)
将字符数组的一部分转成字符串(
- public String(String original)
public class StringDemo2 {
public static void main(String[] args) {
//public String()初始化新创建的String对象,以使其表示空字符序列
String s = new String();
System.out.println(s); //通过这里的结果发现String类重写了toString()方法
System.out.println("=======================================");
//public String(byte[] bytes)通过使用平台的默认字符集解码指定的字节数组来构造新的String 。
// 新的String的长度是字符集的函数,因此可能不等于字节数组的长度。
//将字节数组转成字符串
byte[] bytes = {'a', 'b', 'c', 'd', 'e'};
String s1 = new String(bytes);
System.out.println(s1);
System.out.println("========================================");
//public String(byte[] bytes,int index,int length)
// 通过使用平台的默认字符集解码指定的字节子阵列来构造新的String 。
// 新的String的长度是字符集的函数,因此可能不等于子数组的长度。
//将字节数组的一部分转成字符串
//从下标索引1开始截取,截取3个元素形成一个字符串
// String s2 = new String(bytes, 1, 3);
// System.out.println(s2);
// String s3 = new String(bytes, 1, 10); //StringIndexOutOfBoundsException
// System.out.println(s3);
// String s4 = new String(bytes, 10, 2); //StringIndexOutOfBoundsException
System.out.println("========================================");
//public String(char[] value)分配一个新的String ,以便它表示当前包含在字符数组参数中的字符序列。
// 字符数组的内容被复制; 字符数组的后续修改不会影响新创建的字符串。
//将字符数组转成字符串
char[] chars = {97,98,99,100,101};
String s2 = new String(chars);
System.out.println(s2);
System.out.println("========================================");
// public String(char[] value,int offset,int count)
// 将字符数组的一部分转成字符串(自主完成)
System.out.println("=========================================");
//public String(String original)
String s3 = new String("你好数加");
System.out.println(s3);
}
}
String s3 = new String("你好数加");
System.out.println(s3);
休息一下,看程序,写结果
public class StringDemo5 {
public static void main(String[] args) {
String s = new String();
String s1 = new String("hello");
String s2 = new String("hello");
//String类重写equals方法,所以调用equals方法比较的是两个字符串的内容是否相同
System.out.println(s);
System.out.println(s1==s2);//两个对象的地址值不同,为false
System.out.println(s1.equals(s2));//因为 System.out.println(s); 输出结果为0,证明重写了。重写后比较地址值
System.out.println("================================================");
String s3 = new String("hello");
String s4 = "hello";
System.out.println(s3 == s4);
System.out.println(s3.equals(s4));
System.out.println("====================================================");
String s5 = "hello";
String s6 = "hello";
System.out.println(s5==s6);
System.out.println(s5.equals(s6));
}
}
结果为:
false
true
================================================
false
true
====================================================
true
true
休息一下,看程序,写结果:
++看程序写结果:
当字符串进行拼接的时候,如果是变量相加,会先开辟内存空间,然后再做拼接当字符串进行拼接的时候,++
++如果是常量相加,会先进行拼接,然后在常量池中找,如果找到了就赋值,如果找不到就开辟内存空间赋值++
public class StringDemo6 {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
String s4 = "hello"+"world";
String s5 = s1+s2;
System.out.println(s3==s4);
System.out.println(s3==s5);
//发生哈希碰撞 System.out.println(s3.hashCode());
然后用identityHashCode求地址值
System.out.println(System.identityHashCode(s3));
// System.out.println(s4.hashCode());
System.out.println(System.identityHashCode(s4));
//// System.out.println(s3.equals(s1+s2));
// System.out.println(s5.hashCode());
System.out.println(System.identityHashCode(s5));
}
}
true
false
true
true
460141958
460141958
1163157884
1.3 String类的判断功能
String类的判断功能:
- boolean equals(Object obj):public boolean equals(Object anObject)将此字符串与指定对象进行比较。其结果是true当且仅当该参数不是null并且是String对象,++表示相同的字符序列作为该对象。++
- boolean equalsIgnoreCase(Stringstr):++忽略大小写++的来判断两个值是否相等
- boolean contains(Stringstr): publicbooleancontains(CharSequences)当且仅当此字符串包含指定的char值序列时才返回true。
- boolean startsWith(String str):在括号中输入的和比较的以相同 的字符开头,就就返回true;
- boolean endsWith(String str):用法与startwith差不多;
- boolean isEmpty();判断字符串是否为空
- 注意事项:使用equals比较的时候。可能需要判断的值为null,此时会宝报错;
1.解决方案:将确定的放在前面调用方法,避免发生空指针异常(推荐)
- 解决方案:在比较之前做一次null判断;
代码如下:
*/
public class StringDemo7 {
public static void main(String[] args) {
//创建两个字符串对象
String s1 = "hello";
String s2 = "world";
//public boolean equals(Object anObject)将此字符串与指定对象进行比较。
// 其结果是true当且仅当该参数不是null并且是String对象,表示相同的字符序列作为该对象。
System.out.println(s1.equals(s2));
System.out.println("================================================");
//public boolean equalsIgnoreCase(String anotherString)将此String与其他String比较,忽略案例注意事项。
// 如果两个字符串的长度相同,并且两个字符串中的相应字符等于忽略大小写,则两个字符串被认为是相等的。
String s3 = "heLLO";
// System.out.println(s1.equals(s3));
System.out.println(s1.equalsIgnoreCase(s3));
System.out.println("================================================");
//public boolean contains(CharSequence s)当且仅当此字符串包含指定的char值序列时才返回true。
//判断字符串中是否包含小字符串
System.out.println(s1.contains("ll"));
System.out.println(s1.contains("ho"));
System.out.println("=================================================");
//public boolean startsWith(String s)测试此字符串是否以指定的前缀开头。
//判断大字符串是否以某小字符串开头
System.out.println(s1.startsWith("lo"));
System.out.println(s1.startsWith("h"));
System.out.println(s1.startsWith("hel"));
System.out.println("=================================================");
//boolean endsWith(String str)
//判断大字符串是否以某小字符串结尾
System.out.println(s1.endsWith("w"));
System.out.println(s1.endsWith("ll"));
System.out.println(s1.endsWith("lo"));
System.out.println("=================================================");
//boolean isEmpty()
//判断字符串是否为空
// System.out.println(s1.isEmpty());
String s = "";
String s4 = null;
// System.out.println(s.isEmpty());
// System.out.println(s4.isEmpty()); //NullPointerException
System.out.println("======================================================");
//需求:比较s与是s1的值是否相同
System.out.println(s1.equals(s));
//需求2:判断s1的内容是否是"bigdata"
System.out.println(s1.equals("bigdata"));
s1 = null;
// System.out.println(s1.equals("bigdata")); //NullPointerException
//解决方案1:今后比较两个字符串内容是否相同的时候,把确定的放在前面调用方法,避免发生空指针异常(优先推荐第一种)
System.out.println("bigdata".equals(s1));
//解决方案2:在比较之前,做一次Null判断
if (s1 != null) {
System.out.println(s1.equals("bigdata"));
}else {
System.out.println("字符串s1是为null");
}
}
}
1.4 获取功能:
(重点)String类的获取功能:*****
- int length():返回此字符串的长度。长度等于字符串中的数字Unicode code units
- char charAt(int index):返回char指定索引处的值。 指数范围为0至length() - 1 。该序列的第一个char值在索引0 ,下一个索引为1 ,依此类推,与数组索引一样。++即传入下标索引,返回值为下标对应的值++
- int indexOf(int_char):可以输入字母对应的阿斯科码或者字符会返回字符串中对应的地址值下标
- int indexOf(String_str):返回的是字符串首字母出现在字符串中的位置,如果传入的字符在大串中没有,就会返回 -1;
- int indexOf(intch,intfromIndex):返回指定字符第一次出现的字符串内的索引,以指定的索引开始搜索。找到后返回的是在大串中的地址值。找不到就返回 -1;
int indexOf(String str,int fromIndex)(效果差不多);
- public String_substring(intbeginIndex):)返回一个字符串,该字符串是此字符串的子字符串。子字符串以指定索引处的字符开头,并扩展到该字符串的末尾。
String substring(int start)
(含头不含尾部)String substring(int start,int end)
public class StringDemo8 {
public static void main(String[] args) {
String s = "shujiakeji123";
//public int length()返回此字符串的长度。 长度等于字符串中的数字Unicode code units 。
System.out.println(s.length()); //13
System.out.println("======================================");
//public char charAt(int index)返回char指定索引处的值。 指数范围为0至length() - 1 。
// 该序列的第一个char值在索引0 ,下一个索引为1 ,依此类推,与数组索引一样。
System.out.println(s.charAt(3));
System.out.println(s.charAt(12));
// System.out.println(s.charAt(13)); //IndexOutOfBoundsException - 如果 index参数为负数或不小于此字符串的长度。
System.out.println("=======================================");
//public int indexOf(int ch)返回指定字符第一次出现的字符串内的索引。
// System.out.println(s.indexOf(97));
// System.out.println(s.indexOf('a'));
System.out.println(s.indexOf('z')); //如果此字符串中没有此类字符,则返回-1
System.out.println("=======================================");
//public int indexOf(String str)返回指定子字符串第一次出现的字符串内的索引。
System.out.println(s.indexOf("ake")); // 返回的是字符串首字母出现在字符串中的位置
System.out.println(s.indexOf("spark")); //如果整个字符串在大字符串中不存在,返回-1
System.out.println("=======================================");
//public int indexOf(int ch,int fromIndex)返回指定字符第一次出现的字符串内的索引,以指定的索引开始搜索。
System.out.println(s.indexOf(97,6)); //如果不发生的字符。-1
System.out.println(s.indexOf(97,3)); //如果找到返回的是在整个字符串中的位置索引
System.out.println("=======================================");
//int indexOf(String str,int fromIndex)(自主学习)
System.out.println("=======================================");
//public String substring(int beginIndex)返回一个字符串,该字符串是此字符串的子字符串。
// 子字符串以指定索引处的字符开头,并扩展到该字符串的末尾。
//做字符串截取的
System.out.println(s.substring(4)); //包含开始的位置,一直截取到末尾
System.out.println("========================================");
//String substring(int start,int end) 含头不含尾 [start,end)
System.out.println(s.substring(4,13));
}
}
1.5 String类的转换功能
- byte[] getBytes():使用平台的默认字符集将此String编码为字节序列,将结果存储到新的字节数组中.将字符串转成字节数组
- char[] toCharArray()static: 字符数组 ---> 字符串
- String valueOf(char[] chs) 将int类型的100,转换成String 类型的"100"
- static String valueOf(int i) 将字符数组转成字符串;
- String toLowerCase():全部转小写
- String toUpperCase()全部转大写
- String concat(String str)将两个String类型的字符串进行拼接,
public class StringDemo9 {
public static void main(String[] args) {
String s = "bigDataSPArk";
//public byte[] getBytes()使用平台的默认字符集将此String编码为字节序列,将结果存储到新的字节数组中。
//将字符串转成字节数组
byte[] bytes = s.getBytes();
for (int i = 0; i < bytes.length; i++) {
System.out.println(bytes[i]);
}
System.out.println("=====================================================");
//char[] toCharArray()
// 字符串 ---> 字符数组
//将字符串转成一个字符数组
char[] chars = s.toCharArray();
for(int i = 0;i<chars.length;i++){
if(i==0){
System.out.print("["+chars[i]+",");
}else if(i==chars.length-1){
System.out.print(chars[i]+"]\n");
}else {
System.out.print(chars[i]+",");
}
}
System.out.println("========================================================");
//static String valueOf(char[] chs)
// 字符数组 ---> 字符串
//将字符数组转成一个字符串
String s1 = String.valueOf(chars);
System.out.println(s1);
System.out.println("=========================================================");
//static String valueOf(int i)
// 100 / "100"
String s2 = String.valueOf(100);
System.out.println(s2);
System.out.println("==========================================================");
//String toLowerCase() 将字符串中字符全部转小写 针对于26个字母有效
String s3 = s.toLowerCase();
System.out.println(s3);
// s = "bigDataSPArk我;";
// String s4 = s.toLowerCase();
// System.out.println(s4);
System.out.println("===========================================================");
//String toUpperCase()
String s4 = s.toUpperCase();
System.out.println(s4);
System.out.println("===========================================================");
//String concat(String str) 用于字符串拼接
//需求:现在想在原先的字符串后面拼接上 "今天天气不好"
// s += "今天天气不好";
// System.out.println(s);
System.out.println(s.concat("今天天气不好"));
}
}
1.6 String 的替换功能
1. 替换功能
String replace(char old,char new): 返回从替换所有出现的导致一个字符串oldChar在此字符串newChar。替换字符串中所有的要被替换的字符,返回的是替换后的字符串
String replace(String old,String new):替换字符串中所有的要被替换的字符串,返回的是替换后的字符串
2.去除字符串两空格
String trim():去除字符串两端的空格;
3.按字典顺序比较两个字符串
int compareTo(String str);比较全部一样返回0,否则比较第一个不同值的编码值相减;若字符串长度不相等返回长度的差值
int compareToIgnoreCase(String str):忽略大小写的比较;
public class StringDemo10 {
public static void main(String[] args) {
String s = "hello World Java BIGData trorld";
//public String replace(char oldChar,char newChar)
// 返回从替换所有出现的导致一个字符串oldChar在此字符串newChar 。
// 替换字符串中所有的要被替换的字符,返回的是替换后的字符串
String s1 = s.replace('a', 'q');
System.out.println(s1);
//如果被替换的字符在原字符串中不存在,返回的是原来的字符串
String s2 = s.replace('z', 'p');
System.out.println(s2);
System.out.println("==============================================");
//String replace(String old,String new)
//替换字符串中所有的要被替换的字符串,返回的是替换后的字符串
// String s3 = s.replace("orld", "qwer");
// System.out.println(s3);
// String s3 = s.replace("orld", "qwerdf");
// System.out.println(s3);
//如果被替换的字符串在原字符串中不存在,返回的是原来的字符串
String s3 = s.replace("qwer", "pppppp");
System.out.println(s3);
System.out.println("================================================");
//String trim() 去除字符串两边的所有空格
String s4 = " hello World Java BIGData trorld ";
System.out.println("去除空格之前:");
System.out.println(s4);
String s5 = s4.trim();
System.out.println("去除空格之后:");
System.out.println(s5);
System.out.println("===============================================");
//public int compareTo(String anotherString)按字典顺序比较两个字符串。
// String s6 = "hello"; //h的ASCII码值104
// String s7 = "world"; //w的ASCII码值119
// System.out.println(s6.compareTo(s7));
String s6 = "hello";
String s7 = "hel";
System.out.println(s6.compareTo(s7));
}
}
compareto的源码分析:
public int compareTo(String anotherString) {
//value -- this -- 调用该方法的字符串对应的字符数组 s6 --> {'h','e','l','l','o'}
//anotherString -- s7 -- "hel"
int len1 = value.length; //5
int len2 = anotherString.value.length; //3
int lim = Math.min(len1, len2); //3
char v1[] = value; // {'h','e','l','l','o'}
char v2[] = anotherString.value; // {'h','e','l'}
int k = 0;
while (k < lim) { //0,1,2,3
char c1 = v1[k]; // 'h','e','l' // 'h'
char c2 = v2[k]; // 'h','e','l' // 'w'
if (c1 != c2) {
return c1 - c2; // 104-119 = -15
}
k++;
}
return len1 - len2; //5-3 = 2
}
自我练习;
package com.bigdat.practice.stringdemo;
import java.util.Arrays;
import java.util.Locale;
public class StringD1 {
public static void main(String[] args) {
System.out.println("=========字符串方法的使用 1 =======================");
String num =" 我爱学习BigDate,学习使我快乐";
//1. length求字符串的长度
System.out.println(num.length());
//2.contains(String num)判断字符串是否出现“学习”,出现返回true,否则返回false
System.out.println(num.contains("学习"));
System.out.println(num.contains("Big Date"));
//3.charAT(int index)返回字符串下标对应的值
System.out.println(num.charAt(5));
System.out.println("=========字符串方法的使用 2 =======================");
//4.toCharArray();返回字符串对应的数组
System.out.println(Arrays.toString(num.toCharArray()));
//5.indexof();返回字符串首次出现的位置
System.out.println(num.indexOf("B i"));
System.out.println(num.indexOf("学习",3));
System.out.println(num.lastIndexOf("学习"));
System.out.println("=============字符串方法的使用 3 =======================");
//6.trim() 去掉字符串前后的空格
System.out.println(num.trim());
//7. toUpperCase toLowerCse 将小写转变成大写,和将大写转变成小写
String num1 ="huhuhGGYGvkVhvGHJ";
System.out.println(num1.toUpperCase(Locale.ROOT));
System.out.println(num1.toLowerCase(Locale.ROOT));
//8. endWith()判断是否以某某结尾
System.out.println(num1.endsWith("学习"));
System.out.println("==============字符串方法的使用 4 ==================");
//9. replace(char oldChar,char newChar)将旧的字符串替换成新的字符串
System.out.println(num.replace("学习","美女"));
//10.split();对字符串进行拆分
String say = "java is the best programing language,java xiang-bang-bang";
String[] arr=say.split("[ ,-]+");
System.out.println(arr.length);
for(String string: arr){
System.out.println(string);
}
System.out.println("===========补充:===============================");
String s1 = "HELLO";
String s2 = "hello";
System.out.println(s1.equals(s2));
//忽略大小写的比较
System.out.println(s1.equalsIgnoreCase(s2));
//compareTo(); 比较大小字符
String s3 = "a wuiaf";//97
String s4 = "x wuiaf";//120 120 - 97 字当长度一样时比较符串所在的位置相减 否则比较长度。长度相减
System.out.println(s3.compareTo(s4));
}
}
/*
需求:已知String str = "this is a text";
1.将str中的单词单独获取出来
2.将str中的text替换成practice
3.在text前插入一个easy
4.将每个单词首字母改成大写
*/
public class StringDemo {
public static void main(String[] args) {
String str = "this is a text";
//需求 1
String[] s1 = str.split("[ ]");
for (String s : s1) {
System.out.println(s);
}
//需求 2
String str2 = str.replace("text","practice");
System.out.println(str2);
//需求3
String str3 = str2.replace("practice","easy practice");
System.out.println(str3);
//需求4
for (int i = 0; i < s1.length; i++) {
char first = s1[i].charAt(0);
char upperfirst = Character.toUpperCase(first);
// System.out.println(upperfirst);
String news = upperfirst + s1[i].substring(1);
System.out.println(news);
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?