Cheug's Blog

当前位置:网站首页 / JAVA / 正文

String类

2019-03-21 / JAVA / 880 次围观 / 0 次吐槽 /

String的这个类是final,所以他没有子类

String str = "abc", abc相当于是一个实例对象 "abc"是一个常量区,他是被共享

字符串常量是不能改变值


String构造方法

            public String()

            public String(byte[] bytes):把字节数组转成字符串

            public String(byte[] bytes,int index,int length):把字节数组的一部份转成字符串

            public String(char[] value,int index,int count):把字符数组的一部份转成字符串

            public  String(String original) :初始化一个新创建的 String 对象,使其表示一个与参数相同的字符序列;换句话说,新创建的字符串是该参数字符串的副本


String一些判断功能

            public boolean equals(Object anObject)  判断字符串是否一样

            public boolean equalsIgnoreCase(String anotherString) 判断字符串是否一样,忽略大小写

            public boolean contains(CharSequence s) 判断字符串是否包含哪字符串

            public boolean startsWith(String prefix) 判断字符串是否以什么开头

            public boolean endsWith(String suffix) 判断字符串是否以什么结尾

            public boolean isEmpty() 判断字符串是否为空字符串


字符串比较一个小技巧-避免空指针异常

             把字符串常量放在比较的前面

                         String username = null;

                         "admin".equals(username)


String类的获取功能

                int length():获取字符串的长度

                char charAt(int index):获取指定索引位置的字符

                int indexOf(int ch):获取指定字符在此字符串第一次出现处的索引

                int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引

                int indexOf(int ch,int fromIndex):返回指定字符在此字符串中指定位置后第一次出现处的索引

                int indexOf(String str,int fromIndex):返回指定字符串在此字符串中指定位置后第一次出现处的索引

                lastIndexOf() 最后出现的位置

                String substring(int start):从指定位置开始截取字符串,默认到未尾

                String substring(int start,int end):从指定位置开始到指定位置结束截取字符图


String类转换功能

                byte[] getBytes():把字符串转换为字节数组

                char[] toCharArray():把字符串转换为字符数组

                static String valueOf(char[] chs):把字符数组转成字符串

                static String valueOf(int i):把int类型的数据转成字符串

                                        注意:String类的valueOf方法可以把任意类型的数据转成字符串

                String toLowerCase():把字符串转成小写

                String toUpperCase():把字符串转成大写

                String concat(String str):把字符串拼接,且只能拼接字符串。+方式拼接字符串时,可以是任意类型


String类的其它功能

                public String replace(char oldChar, char newChar)//替换字符

                public String replace(CharSequence target, CharSequence replacement) //替换字符串

                String trim();//去除前后空格

                public int compareTo(String anotherString) //比较字符串的大小

                public int compareToIgnoreCase(String str) //不区分大小写比较字符串大小


额 本文暂时没人评论 来添加一个吧

发表评论

必填

选填

选填

必填

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

Powered By Cheug's Blog

Copyright Cheug Rights Reserved.