java string筆試常見函數

來源:互聯網
上載者:User

今天筆試裡面有很多String的問題,就是SubString、IndexOf之類的東西,呵呵,覺得都還可以了,但是遇到了個concat,困擾了我好一會,真的從來沒有用過這個,回來一看才發現就是這麼個!嘿嘿!

 

String a = "ABC";
  String b = "DEF";

  a.concat(b);
  System.out.println(a);

  String s = "hello";
  System.out.println("cares".concat(s));
  System.out.println("".concat("hello"));
  System.out.println("to".concat("get").concat("her"));

 

大家猜猜看是什麼結果:

 

ABC
careshello
hello
together

 

 

呵呵,我也覺得挺驚訝的,所以看了下java API,如下:

  public String concat(String str)

 {
 int otherLen = str.length();
 if (otherLen == 0)

{
     return this;
 }
 char buf[] = new char[count + otherLen];
 getChars(0, count, buf, 0);
 str.getChars(0, otherLen, buf, count);
 return new String(0, count + otherLen, buf);
   }

 

原來如此啊:

String a = "ABC";
  String b = "DEF";

  a.concat(b);
  System.out.println(a);
  System.out.println("ABC".concat(b));

 

結果是:

ABC
ABCDEF

不用過多的解釋大家也可以明白了吧,嘿嘿,很有意思

 

下面是幾個java中String常用的文文書處理函數

 

①java.lang.String-->substring(int indexId)/String substring(int beginIdex,int endIndex)
得到子串:"unhappy".substring(2)-->"happy"(截取從indexId開始到結束的串)
        "emptiness".substring(20)-->""(返回空串)
        "hamburger".substring(4,8)-->"urger"
        "hamburger".substring(4,20)-->"java.lang.StringIndexOutOfBoundsException"異常
對於java.lang.StringBuffer/StringBuilder都相同用法!
② java.long.String.concat

    "cares".concat(s)-->"caress"
         "".concat("hello")-->"hello"
         "to".concat("get").concat("her")-->"together"
這個方法只有String類裡有
③java.lang.String.charAt(int index):char(根據index取得對應位置的字母)
         "hello".charAt(4)-->‘o’有可能拋出異常IndexOutOfBoundsException
④java.lang.String.lenght()這個就沒什麼可說了,但別忘記數組對象沒有這個函數
⑤java.lang.String.contentEquals(StringBuffer compStr):boolean
如果比較的String與compStr裡的內容完全一致的話就返回true
⑥java.lang.String.startsWith(String prefix):boolean
java.lang.String.endsWith(String suffix):boolean
就判斷一個字串是否以串開頭、結尾
⑦java.lang.String.indexOf(String str)/lastIndexOf(String str)
取得第一次/最後一次匹配str的位置
⑧java.lang.String.split(String regEx):String[]
根據RegexregEx來切割字串
⑨java.lang.String.toUpperCase()/toLowerCase把串都變成大寫/小寫
⑩java.lang.String.toCharArray():char[]把串打散成字元數組
⑪public String intern()若且唯若string1.equals(string2)
⑫public String replaceAll(String regex,String replacement)/replaceFirst(String oldStr,String newStr)
替換字串
⑬java.lang.String.trim()去除字串的兩端空格符

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.