码迷,mamicode.com
首页 > 编程语言 > 详细

[javaSE] 基本类型(String相关)

时间:2016-05-15 02:31:41      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:

字符串是一个特殊的对象

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

 

获取字符串的长度

调用String对象的length()方法,返回int长度

 

获取某个索引位置的字符

调用String对象的charAt()方法,得到char字符,参数:int类型的索引

 

根据字符获取在字符串中的索引位置

调用String对象的indexOf()方法,得到第一次出现的int索引位置,返回-1就是不存在,参数:String类型字符串

 

获取子字符串,根据索引

调用String对象的substring()方法,参数:int类型开始索引

 

判断字符串是否有内容

调用String对象的isEmpty()方法,得到布尔值

 

判断字符串中是否包含另一个字符串

调用String对象的contains()方法,得到布尔值,参数:String对象

 

转换基本数据类型成字符串

调用String.valueOf(),参数:基本数据类型

 

转换字符串成字符数组

调用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");// 输出 12
echo $str{8};// 输出 n;这个方法中文乱码,PHP中没有类似charAt()方法
echo strpos($str,"陶");//输出 9
echo 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涵陶士涵

 

[javaSE] 基本类型(String相关)

标签:

原文地址:http://www.cnblogs.com/taoshihan/p/5494357.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!