0
点赞
收藏
分享

微信扫一扫

Java中的String类的基本使用方法


String类概述

java.lang.String 类代表字符串。Java程序中所有的字符串文字(例如 “abc” )都可以被看作是实现此类的实例。
类 String 中包括用于检查各个字符串的方法,比如用于比较字符串,搜索字符串,提取子字符串以及创建具有翻译为大写或小写的所有字符的字符串的副本。

String对象是不可变的

因为String对象是不可变的,所以它们可以被共享。

String s1 = "abc";
String s2 = "abc";
// **内存中只有一个"abc"对象被创建,同时被s1和s2共享**

String底层是靠字符数组实现的

“abc” 等效于 char[] data={ ‘a’ , ‘b’ , ‘c’ }
例如:
String str = “abc”;
相当于:
char data[] = {‘a’, ‘b’, ‘c’};
String str = new String(data);

创建方式

public String() :初始化新创建的 String对象,以使其表示空字符序列。
public String(char[] value) :通过当前参数中的字符数组来构造新的String。
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 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。

转换功能的方法

  1. public char[] toCharArray () :将此字符串转换为新的字符数组。
  2. public byte[] getBytes () :使用平台的默认字符集将该 String编码转换为新的字节数组。
  3. public String replace (CharSequence target, CharSequence
    replacement) :将与target匹配的字符串使用replacement字符串替换。

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
}
}
}

新创建一个公众号 Rockey小何同学 想相互交流的同学可以关注一下哈! 感谢支持!


举报

相关推荐

0 条评论