模拟实现字符串的基本操作

模拟实现字符串的基本操作
1.字符串比较
1.1
equals 区分大小写的比较
equalsIgnoreCase 不区分大小写的比较

String str1 = "hello world";
String str2 = "Hello World";
System.out.println(str1.equals(str2));//false
System.out.println(str1.equalsIgnoreCase(str2));//true

1.2
compareTo 比较两个字符串的大小关系,是一个非常重要的方法,该方法返回一个整型,该数据会根据大小关系返回三类内容:
相等:返回0.
小于:返回内容小于0.
大于:返回内容大于0.

System.out.println("A".compareTo("a"));//-32
System.out.println("a".compareTo("a"));//0
System.out.println("a".compareTo("A"));//32

2.字符串查找
2.1
contains 判断一个子字符串是否存在

String str1 = "hello world";
String str2 = "world";
System.out.println(str1.contains(str2));//true

2.2
public int indexOf(String str)从头开始查找指定字符串的位置,查到了返回位置的开始索引,查不到返回-1.
public int indexOf(String str,int fromIndex)从指定位置查找子字符串的位置
public int lastIndexOf(String str)从后向前查找子字符串的位置,返回由前向后数的下标
public int lastIndexOf(String str,int formIndex)从指定位置由后向前查找

String str = "helloworld";
System.out.println(str.indexOf("w"));//5
System.out.println(str.indexOf("low"));//3
System.out.println(str.indexOf("l",5));//8
System.out.println(str.lastIndexOf("w"));//5
System.out.println(str.lastIndexOf("l",4));//3

3.字符串的替换
3.1
replaceAll 替换所有指定内容
replaceFirst 替换首个内容
注意事项: 由于字符串是不可变对象, 替换不修改当前字符串, 而是产生一个新的字符串.

String str = "helloworld";
System.out.println(str.replaceAll("l","_"));//he__owor_d
System.out.println(str.replaceFirst("l","_"));//he_loworld

4.字符串的拆分
4.1
可以将一个完整的字符串按照指定的分隔符划分为若干个子字符串。
public String[] split(String regex) 将字符串全部拆分
public String[] split(String regex,int limit)将字符串部分拆分,该数组长度就是limit极限

String str = "we are happy";
String[] result = str.split(" ");//按照空格拆分
for (String i : result) {
    System.out.println(i);
}
String str = "we are happy !";
String[] result = str.split(" ",3);//按照空格拆分
for (String i : result) {
    System.out.println(i);
}

多次拆分

String str = "name=zhangsan&age=18" ;
String[] result = str.split("&") ;
for (int i = 0; i < result.length; i++) {
    String[] tmp = result[i].split("=") ;
    System.out.println(tmp[0]+" = "+tmp[1]);

在这里插入图片描述
5.字符串的截取
5.1
public int substring(int beginIndex) 从指定位置截取到结尾
public int substring(int beginIndex,int endIndex) 截取部分内容,
注意事项:
索引从0开始
注意前闭后开区间的写法,(2,5)表示包含 2 号下标的字符, 不包含 5 号下标

String str = "helloworld";
System.out.println(str.substring(3));//loworld
System.out.println(str.substring(2,5));//llo

6.其他操作
6.1
trim 去掉字符串中的左右空格,保留字符串内部空格

String str = "   hello world   ";
System.out.println("["+str+"]");
System.out.println("["+str.trim()+"]" );

在这里插入图片描述
6.2
length 取得字符串长度
注意:数组长度使用数组名称.length属性,而String中使用的是length()方法

String str = "hello world";
System.out.println(str.length());//11

6.3
public boolean isEmpty() 判断是否为空字符串,但不是null,而是长度0.

System.out.println("hello".isEmpty());//false
System.out.println("".isEmpty());//true
System.out.println(new String().isEmpty());//true

6.4
toCharArray 将字符串转化为新的字符数组.

String str = "hello world";
char[] c = str.toCharArray();
System.out.println(c);
发布了60 篇原创文章 · 获赞 23 · 访问量 3321

猜你喜欢

转载自blog.csdn.net/weixin_44945537/article/details/102901329