Java String API详解 - 不知道的就不懂Java

一、前言

众所周知,无论使用哪一门编程语言,和字符串打的交道总是非常之多的。如果恰好使用的编程语言在字符串处理方面,API很全的话,就可以省去很多麻烦。就现在的使用体验来说,JAVA在字符串处理方面还是挺方便的。这篇博文主要是给大家总结一下java中,有关String的那些常见的API,日后大家使用时,可以方便大家查询。

二、常见API

  • 构造器

Java中,一切皆对象,String也是。如果是对象的话,那第一个想到的函数自然而然就是构造器啦!语法如下:

String str = new String("I am a lucky string."); //构造器
我们知道String的初始化还有另外一种方式
String str = "I am a lucky string"
这两种初始化方式有区别吗?回答是,当然有,区别还不小。不过本文在这一方面就不赘述了,想要了解的同学可以参考这篇博客点击打开链接
  • length()
length求一个字符串的长度,如下所示
System.out.println("My length is " + str.length()); //length()
  • charAt()
char charAt(int index),返回String中index下标位置处的char,若index不合法,抛出IndexOutOfBoundsException异常。例子如下:
System.out.println("My favoriate character is " + str.charAt(8));  //charAt() Output:u
  • getChars
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin),将String源中下标从srcBegin到srcEnd的字符串,复制到目标字符串中,从下标从dstBegin开始复制。当然如果下标有一个不合法,也会抛出IndexOutOfBoundsException异常。例子如下:
char dst[] = {'a', 'p', 'o', 'o', 'r', 'g', 'i', 'r', 'l'};
		System.out.println("Now I want to pass my lucky to a good guy");
		str.getChars(7, 12, dst, 0);    //getChars(),Output:luckygirl
  • getBytes()
用平台默认的编码方式对String进行编码,并将结果储存到一个新的byte数组中。例子如下:
byte[] b_gbk = str.getBytes();  //getBytes()
  • toCharArray()
将String转换成一个char数组,例子如下:
dst = str.toCharArray(); //toCharArray()
System.out.println(dst);   //output:I am a lucky string.
  • equals()
public boolean equals(Object anObject)比较源String和anObject内容是否相等,注意“=”比较的是引用是否相等。二者的差别本文也不赘述,详情请见点击打开链接

  • equalsIgnoreCase()
用法类似equals(),只不过比较时忽略大小写。
  • compareTo()
public int compareTo(String anotherString),按字典顺序比较两个String的大小哦。字典顺序是说a<b<c,返回值有三种可能:1,0,-1分别表示大于,等于,小于。例子如下:
if (str.compareTo("I am a unlucky string.") > 0) {   //compareTo(),Output:I am smaller
	System.out.println("I am bigger");
} else {
	System.out.println("I am smaller");
}
  • contains()
boolean contains(CharSequence s),判断源String中是否含有s。包含则返回1,不包含则返回0。关于什么是CharSequence,本文不赘述,请自行百度。例子如下:
if (str.contains("lucky")) {                             //contains(),Output:<span style="font-family: Arial, Helvetica, sans-serif;">I contain lucky word</span>
	System.out.println("I contain lucky word");
} else {
	System.out.println("I don't contain lucky word");
}

  • contentEquals()
boolean contentEquals(StringBuffer sb),方法比较字符串到指定的CharSequence。其结果是true当且仅当此String指定序列相同的char值序列。例子如下:
StringBuffer strBuf = new StringBuffer("I am a lucky string.");
	if (str.contentEquals(strBuf)) {                             //contentEquals(),Output:The same
		System.out.println("The same");
	} else {
		System.out.println("Diffenent");
	}
  • regionMatches()
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)。第一个参数ignoreCase表示比较时是否需要忽略大小,从toffset下标开始比较String和从下表ooffset开始String other是否相等,len表示指定比较的长度。例子如下:
String strNew = new String("I AM A LUCKY STRING.");
		if (str.regionMatches(true, 7, strNew, 7, 5)) {                             //regionMatches()
			System.out.println("The same");  //输出这一行
		} else {
			System.out.println("Diffenent");
		}
  • startsWith()
boolean startsWith(String prefix)判断是否以prefix开头,是返回true,反之,则返回false
  • boolean endsWith(String suffix)
判断是否以prefix结尾,是返回true,反之,则返回false
  • indexOf()
int indexOf(int ch),从左往右查找ASCII码为ch的字符,如果存在则返回该字符的下标。如果不存在,则返回-1
  • lastIndexOf()
int indexOf(int ch),从右往左查找ASCII码为ch的字符,如果存在则返回该字符的下标。如果不存在,则返回-1。和上面indexof一起的例子如下所示:
System.out.println(str.indexOf(97));          //indexOf()     输出:2   
		System.out.println(str.lastIndexOf(97));         //lastIndexOf() 输出:5
  • substring()
String substring(int beginIndex, int endIndex),返回String下标从beginIndex到下标endIndex-1之间的字符串。例子如下:
System.out.println(str.substring(7, 11));        //substring,输出:	luck
  • concat()
拼接两个字符串。例子如下:
System.out.println(str.concat(" Do you like me? "));        //concat,输出:I am a lucky string. Do you like me?
  • replace()
String replace(char oldChar, char newChar),从这个函数原型中就可以看出就是将String中的oldChar替换成newChar啦。是全部替换哦,例子如下:
System.out.println(str.replace('a', 'A'));        //replace,输出:I Am A lucky string.
  • toUpperCase()和toLowerCase()
不解释,转成大写/小写。
  • trim()
将String两端的空白字符删除后,返回一个新的String对象。如果没有改变发生,则返回原String对象。例子如下:
strNew = "          I am a lucky string.            ";
		System.out.println(strNew.trim());        //trim,输出:I am a lucky string.
  • valueOf()
返回一个表示参数内容的String,参数可以是double,int,float,char,char[],long啊之类的,基本都可以。实际上就是类型转换啦!把别的类型的数据转换成String。例子如下:
System.out.println(str.valueOf(8.8));      //valueOf输出:8.8
  • intern()
为每一个唯一的字符序列生成且仅生成一个String引用。什么意思呢?就是说某一个字符序列已经存在的话,那么就返回该字符序列对应的引用,例子如下:
System.out.println(str3 == str4);         //输出:false
		str4 = (str1 + str2).intern();            //重点:intern()
		System.out.println(str3 == str4);         //输出:true

三、程序完整版

public class StringClass {
	
	public static void main(String[] args) {
		String str = new String("I am a lucky string."); //构造器
		System.out.println("My length is " + str.length()); //length()
		System.out.println("My favoriate character is " + str.charAt(8));  //charAt() Output:u
		char dst[] = {'a', 'p', 'o', 'o', 'r', 'g', 'i', 'r', 'l'};
		System.out.println("Now I want to pass my lucky to a good guy");
		str.getChars(7, 12, dst, 0);    //getChars(),Output:luckygirl
		System.out.println(dst);
		byte[] b_gbk = str.getBytes();  //getBytes()
		System.out.println(b_gbk);
		dst = str.toCharArray(); //toCharArray()
		System.out.println(dst);   //output:I am a lucky string.
		
		if (str.equals("I am a unlucky string.")) {   //equals()
			System.out.println("The same");
		} else {
			System.out.println("Diffenent");
		}
		
		if (str.equalsIgnoreCase("I AM A LUCKY STRING.")) {   //equalsIgnoreCase()
			System.out.println("The same");
		} else {
			System.out.println("Diffenent");
		}
		
		if (str.compareTo("I am a unlucky string.") > 0) {   //compareTo(),Output:I am smaller
			System.out.println("I am bigger");
		} else {
			System.out.println("I am smaller");
		}
		
		if (str.contains("lucky")) {                             //contains()
			System.out.println("I contain lucky word");
		} else {
			System.out.println("I don't contain lucky word");
		}
		
		StringBuffer strBuf = new StringBuffer("I am a lucky string.");
		if (str.contentEquals(strBuf)) {                             //contentEquals(),Output:The same
			System.out.println("The same");
		} else {
			System.out.println("Diffenent");
		}
		
		String strNew = new String("I AM A LUCKY STRING.");
		if (str.regionMatches(true, 7, strNew, 7, 5)) {                             //regionMatches()
			System.out.println("The same");
		} else {
			System.out.println("Diffenent");
		}
		
		if (str.startsWith("I")) {                             //startsWith()
			System.out.println("I start with I.");
		} else {
			System.out.println("I don't start with I.");
		}
		
		if (str.endsWith("string.")) {                             //endsWith()
			System.out.println("I end with string.");
		} else {
			System.out.println("I don't end with string.");
		}
		
		System.out.println(str.indexOf(97));          //indexOf()        
		System.out.println(str.lastIndexOf(97));         //lastIndexOf()
		System.out.println(str.substring(7, 11));        //substring,输出:	luck	
		System.out.println(str.concat(" Do you like me? "));        //concat,输出:I am a lucky string. Do you like me?	
		System.out.println(str.replace('a', 'A'));        //replace,输出:I Am A lucky string.
		System.out.println(str.toUpperCase());            //toUpperCase
		strNew = "          I am a lucky string.            ";
		System.out.println(strNew.trim());        //trim,输出:I am a lucky string.
		System.out.println(str.valueOf(8.8));      //valueOf输出:8.8
		
		
		String str1 = "a"; 
		String str2 = "bc"; 
		String str3 = "a"+"bc"; 
		String str4 = str1+str2; 

		System.out.println(str3 == str4);         //输出:false
		str4 = (str1 + str2).intern();            //重点:intern()
		System.out.println(str3 == str4);         //输出:true
	}
}

如有不足之处,欢迎指出。
  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java String API 测试代码 1.String和char[]之间的转换 toCharArray(); 2.String和byte[]之间的转换 getBytes() Arrays工具 : Arrays.toString(names) String String replace(char oldChar, char newChar) String replace(CharSequence target, CharSequence replacement) String[] split(String regex) boolean contains(CharSequence s):当且仅当此字符串包含指定的 char 值序列时,返回 true int indexOf(String str):返回指定子字符串在此字符串中第一次出现处的索引 int indexOf(String str, int fromIndex):返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始 int lastIndexOf(String str):返回指定子字符串在此字符串中最右边出现处的索引 int lastIndexOf(String str, int fromIndex):返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索 boolean endsWith(String suffix):测试此字符串是否以指定的后缀结束 boolean startsWith(String prefix):测试此字符串是否以指定的前缀开始 boolean startsWith(String prefix, int toffset):测试此字符串从指定索引开始的子字符串是否以指定前缀开始 int length():返回字符串的长度: return value.length char charAt(int index): 返回某索引处的字符return value[index] boolean isEmpty():判断是否是空字符串:return value.length == 0 String toLowerCase():使用默认语言环境,将 String 中的所有字符转换为小写 String toUpperCase():使用默认语言环境,将 String 中的所有字符转换为大写 String trim():返回字符串的副本,忽略前导空白和尾部空白 boolean equals(Object obj):比较字符串的内容是否相同 boolean equalsIgnoreCase(String anotherString):与equals方法似,忽略大小写 String concat(String str):将指定字符串连接到此字符串的结尾。 等价于用“+” String substring(int beginIndex):返回一个新的字符串,它是此字符串的从beginIndex开始截取到最后的一个子字符串。 String substring(int beginIndex, int endIndex) :返回一个新字符串,它是此字符串从beginIndex开始截取到endIndex(不包含)的一个子字符串。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值