Java String API详解

    xiaoxiao2021-03-25  127

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

    二、常见API

    构造器

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

    [java]  view plain  copy   String str = new String("I am a lucky string."); //构造器   我们知道String的初始化还有另外一种方式 [java]  view plain  copy   String str = "I am a lucky string"   这两种初始化方式有区别吗?回答是,当然有,区别还不小。不过本文在这一方面就不赘述了,想要了解的同学可以参考这篇博客点击打开链接 length() length求一个字符串的长度,如下所示 [java]  view plain  copy   System.out.println("My length is " + str.length()); //length()   charAt() char charAt(int index),返回String中index下标位置处的char,若index不合法,抛出IndexOutOfBoundsException异常。例子如下: [java]  view plain  copy   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异常。例子如下: [java]  view plain  copy   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(712, dst, 0);    //getChars(),Output:luckygirl   getBytes() 用平台默认的编码方式对String进行编码,并将结果储存到一个新的byte数组中。例子如下: [java]  view plain  copy   byte[] b_gbk = str.getBytes();  //getBytes()   toCharArray() 将String转换成一个char数组,例子如下: [java]  view plain  copy   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分别表示大于,等于,小于。例子如下: [java]  view plain  copy   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,本文不赘述,请自行百度。例子如下: [java]  view plain  copy   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值序列。例子如下: [java]  view plain  copy   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表示指定比较的长度。例子如下: [java]  view plain  copy   String strNew = new String("I AM A LUCKY STRING.");           if (str.regionMatches(true7, strNew, 75)) {                             //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一起的例子如下所示: [java]  view plain  copy   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之间的字符串。例子如下: [java]  view plain  copy   System.out.println(str.substring(711));        //substring,输出:    luck   concat() 拼接两个字符串。例子如下: [java]  view plain  copy   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啦。是全部替换哦,例子如下: [java]  view plain  copy   System.out.println(str.replace('a''A'));        //replace,输出:I Am A lucky string.   toUpperCase()和toLowerCase() 不解释,转成大写/小写。 trim() 将String两端的空白字符删除后,返回一个新的String对象。如果没有改变发生,则返回原String对象。例子如下: [java]  view plain  copy   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。例子如下: [java]  view plain  copy   System.out.println(str.valueOf(8.8));      //valueOf输出:8.8   intern() 为每一个唯一的字符序列生成且仅生成一个String引用。什么意思呢?就是说某一个字符序列已经存在的话,那么就返回该字符序列对应的引用,例子如下: [java]  view plain  copy   System.out.println(str3 == str4);         //输出:false           str4 = (str1 + str2).intern();            //重点:intern()           System.out.println(str3 == str4);         //输出:true  

    三、程序完整版

    [java]  view plain  copy   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(712, 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(true7, strNew, 75)) {                             //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(711));        //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       }   }  
    转载请注明原文地址: https://ju.6miu.com/read-11586.html

    最新回复(0)