[javaSE] 基本類型(String相關),javasestring

來源:互聯網
上載者:User

[javaSE] 基本類型(String相關),javasestring

字串是一個特殊的對象

字串一旦初始化就不可以被改變

 

擷取字串的長度

調用String對象的length()方法,返回int長度

 

擷取某個索引位置的字元

調用String對象的charAt()方法,得到char字元,參數:int類型的索引

 

根據字元擷取在字串中的索引位置

調用String對象的indexOf()方法,得到第一次出現的int索引位置,返回-1就是不存在,參數:String類型字串

 

擷取子字串,根據索引

調用String對象的substring()方法,參數:int類型開始索引

 

判斷字串是否有內容

調用String對象的isEmpty()方法,得到布爾值

 

判斷字串中是否包含另一個字串

調用String對象的contains()方法,得到布爾值,參數:String對象

 

轉換基礎資料型別 (Elementary Data Type)成字串

調用String.valueOf(),參數:基礎資料型別 (Elementary Data Type)

 

轉換字串成字元數組

調用String對象的toCharArray()方法,得到位元組數組

 

轉換字串成位元組數組

調用String對象的getBytes()方法,得到byte[]位元組數組

 

轉換字串為字串數組,按照指定字元

調用String對象的split()方法,參數:String字串

 

替換字串

調用String對象的replace()方法,參數:舊字串,新字串

 

public class StringDemo {    /**     * @param args     */    public static void main(String[] args) {        String name="taoshihan陶士涵";        System.out.println(name.length());//輸出 12        System.out.println(name.charAt(9));//輸出 陶        System.out.println(name.indexOf("陶"));//輸出 9        System.out.println(name.substring(9));//輸出 陶士涵        System.out.println(name.contains("shi"));//輸出 true        System.out.println(String.valueOf(1));//輸出 1        System.out.println(name.toCharArray());//輸出 taoshihan陶士涵        System.out.println(name.getBytes());//輸出[B@6a754384        System.out.println(name.split("n"));//輸出 [Ljava.lang.String;@77a477b7        System.out.println(name.replace("han", "涵"));//輸出 taoshi涵陶士涵    }}

 

PHP版,完全對應

<?php$str="taoshihan陶士涵";echo mb_strlen($str,"utf-8");// 輸出 12echo $str{8};// 輸出 n;這個方法中文亂碼,PHP中沒有類似charAt()方法echo strpos($str,"陶");//輸出 9echo mb_substr($str,9);//輸出 陶士涵echo strstr($str, "shi");//輸出 shihan陶士涵echo (string)1;//輸出 1//PHP沒有字串轉字元數組內建方法//PHP沒有字串轉位元組數組內建方法print_r(explode("n", $str));//輸出 Array ( [0] => taoshiha [1] => 陶士涵 )echo str_replace("han","涵",$str);// 輸出 taoshi涵陶士涵

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.