String类

15 篇文章 0 订阅

String类

构造函数

1.public String() :初始化新创建的 String对象,以使其表示空字符序列。
2.public String(char[] value) :通过当前参数中的字符数组来构造新的String。
3.public String(byte[] bytes) :通过使用平台的默认字符集解码当前参数中的字节数组来构造新的
String。

String str = new String();

// 通过字符数组构造
char chars[] = {'a', 'b', 'c'};
 String str2 = new String(chars);

// 通过字节数组构造
byte bytes[] = { 97, 98, 99 }; 
String str3 = new String(bytes);`

字符串比较

1.public boolean equals (Object anObject):将此字符串与指定对象进行比较。
2.public boolean equalsIgnoreCase (String anotherString):将此字符串与指定对象进行比较,忽略大小写。

public class String_Demo01 {
public static void main(String[] args) {
// 创建字符串对象
String s1 = "hello"; 
String s2 = "hello"; 
String s3 = "HELLO";

// boolean equals(Object obj):比较字符串的内容是否相同
System.out.println(s1.equals(s2)); // true 
System.out.println(s1.equals(s3)); // false 
System.out.println("‐‐‐‐‐‐‐‐‐‐‐");

//boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写 
System.out.println(s1.equalsIgnoreCase(s2)); // true 
System.out.println(s1.equalsIgnoreCase(s3)); // true 
System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
}
}

获取功能的方法

1.public int length ():返回此字符串的长度。
2.public String concat (String str):将指定的字符串连接到该字符串的末尾。
3.public char charAt (int index):返回指定索引处的 char值。
4.public int indexOf (String str):返回指定子字符串第一次出现在该字符串内的索引。
5.public String substring (int beginIndex):返回一个子字符串,从beginIndex开始截取字符串到字符串结尾。
6.public String substring (int beginIndex, int endIndex):返回一个子字符串,从beginIndex到endIndex截取字符串。含beginIndex,不含endIndex。

转换功能的方法

在这里插入图片描述

public class String_Demo03 {
public static void main(String[] args) {
//创建字符串对象String s = "abcde";

// char[] toCharArray():把字符串转换为字符数组char[] chs = s.toCharArray();
for(int x = 0; x < chs.length; x++) { System.out.println(chs[x]);
}
System.out.println("‐‐‐‐‐‐‐‐‐‐‐");

// byte[] getBytes ():把字符串转换为字节数组byte[] bytes = s.getBytes();
for(int x = 0; x < bytes.length; x++) { System.out.println(bytes[x]);
}
System.out.println("‐‐‐‐‐‐‐‐‐‐‐");

// 替换字母it为大写IT
String str = "itcast itheima";
String replace = str.replace("it", "IT"); System.out.println(replace); // ITcast ITheima System.out.println("‐‐‐‐‐‐‐‐‐‐‐");
}
}

分割功能的方法

public String[] split(String regex):将此字符串按照给定的regex(规则)拆分为字符串数组。

public class String_Demo03 {
public static void main(String[] args) {
//创建字符串对象
String s = "aa|bb|cc";
String[] strArray = s.split("|"); // ["aa","bb","cc"] for(int x = 0; x < strArray.length; x++) {
System.out.println(strArray[x]); // aa bb cc
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值