java-String及其常用API

来源:互联网 发布:中国程序员数量 编辑:程序博客网 时间:2024/05/21 18:00
package day_7_23;/** * String是不可变对象 * java.lang.String使用了final修饰,不能被继承; * 字符串底层封装了字符数组及针对字符数组的操作算法; * 字符串一旦创建,对象永远无法改变,但是字符串引用可以重新赋值 * java字符串在内存中采用Unicode编码方式,任何一个字符对应两个字节的定长编码 * *int indexOf(String str):返回在字符串中str第一次出现的位置,若没有返回-1 *int indexOf(String str,int fromIndex):从字符串的fromIndex中开始检索 *int lastIndexOf(String str):str在字符串上出现多次,则在最后一次出现的位置 * *String substring(int strat):截取从start(包括)下标开始到字符串结尾的字符串并返回 *String substring(int start,int end):截取当前字符串指定范围内的字符串并返回,在java api中通常使用两个数字表示范围时,都是“含头不含尾” * */public class Str {    public static void main(String[] args) {            String s1="123a";            String s2="123a";            String s3="123b";            System.out.println(s1==s2);//true            System.out.println(s1==s3);//false            String s4=123+"a";//编译器编译程序时若发现一个计算表达式则所有内容都是直接量,就直接算成“123a”            System.out.println(s1==s4);//true            String s="123";            String s5=s+"a";//编译器发现左边为变量就重新分配地址值            System.out.println(s1==s5);//false         //字符串的下标:012345678            String str="839756abc";            System.out.println(str.indexOf("756"));//3            System.out.println(str.indexOf("a",6));//6            System.out.println(str.substring(2));//9756abc            System.out.println(str.substring(0, 2));//83            System.out.println(str.charAt(8));//c            String a="http://www.baidu.com";            String b="http://www.jindong.com";            System.out.println(getHostName(a)+","+getHostName(b));            //char charAt(int index):返回当前字符串中指定位置的字符-----查看字符串是否是回文            String a1="上海自来水来自海上";            for(int i=0,j=a1.length()-1;i<a1.length()/2;i++,j--) {                if(a1.charAt(i)!=a1.charAt(j)) {                    System.out.print("不");                    break;                }            }            System.out.println("是回文");            /**String trim():去除当前字符两边的空白字符**/            String use="    kkk KK ";            System.out.println(use.trim());            //boolean startsWith(String str):判断字符串是否以给定字符串开始            //boolean endsWith(String str):判断字符串是否以给定字符串结束            String us="学生.txt";            System.out.println("学生.txt "+us.endsWith(".txt"));            /**             * static String valueOf(...)             * String提供了一组重载的静态方法valueOf             * 作用是将java其他类型转换为字符串             * 常用于             */            int a3=123;            double a4=123456.65;            float a5=90.3f;            System.out.println(String.valueOf(a3)+";"+String.valueOf(a4)+";"+a5);            /**             * String toUpperCase():将当前字符串中的英文部分转换为全大写             * String toLowerCase():将当前字符串中的英文部分转换为全小写             */            String tu="java我爱学习";            System.out.println(tu.toUpperCase());    }    public static String getHostName(String host) {        int start=host.indexOf(".")+1;//获取第一次出现.的下个字符的下标        int end =host.indexOf(".",start);        return host.substring(start,end);    }}
原创粉丝点击