javaSE三个特殊的类 -- String类&String类面试题

String类

String类

  • String的两种实例化方式

            直接赋值(用的最多)

                String str=“Hello”;

            传统方法,实例化对象

                String str=new String("Hello");

  • 字符串相等比较

            str.equals(str1);   //比较的是内容

            public boolean equals(String str1)

  • 字符串常量是String类的匿名对象

            tips:在指定内容比较时,将指定内容(字符串常量)写在前面,避免NullPointException

          

面试题:请解释String类“==”与“equals”的区别

  1. “==”:进行的是数值比较,比较的是两个字符串对象的内存地址数值

  2. equals()”:可以进行字符串内容的比较

  • String采用共享设计模式   在JVM底层自动维护一个字符串对象池(对象数组)。

      如果采用直接赋值的模式进行String类的对象实例化操作,此对象将自动保存到对象池中,如果有,直接引用,如果没有,开辟新的空间将其保存到对象池中共下次使用;

      对象池就是一个对象数组目的就是减少内存的开销

      字符串手工入池操作:

      public native String intern();

范例:


  
  
  1. // 该字符串常量并没有保存在对象池之中
  2. String str1 = new String( "hello");
  3. String str2 = "hello" ;
  4. System.out.println(str1 == str2); // false
  5. ----------------------------------
  6. ----------------------------------
  7. // 使用手动入池操作
  8. String str1 = new String( "hello").intern() ;
  9. String str2 = "hello" ;
  10. System.out.println(str1 == str2); // true

面试题:请解释String类中两种对象实例化的区别

  1. 直接赋值 就会自动采用共享模式,只会开辟一块堆内存空间,并且该字符串对象可以自动保存在对象池中以供下次使用。

  2. 构造方法 就会开辟两块堆内存空间并且其中一块堆内存将成为垃圾空间,不会自动保存在对象池中,可以使用intern()方法手工入池。

        

  • 字符串常量不可变更

            字符串常量一旦定义不可改变

范例:观察如下代码


  
  
  1. String str = "hello" ;
  2. str = str + " world" ;
  3. str += "!!!" ;
  4. System.out.println(str); // hello world!!!

以上字符串变更是字符串对象变更非字符串常量

内存中的字符串修改如下图所示:

可以发现字符串上没有发生变化,但是字符串对象的引用一直在改变,并且形成了大量垃圾空间。正是因为 String的特点,所以如下代码不应该在你的开发中出现:


  
  
  1. String str = "hello" ;
  2. for( int x = 0 ; x< 1000 ; x++) {
  3. str += x ;
  4. }
  5. System.out.println(str)

如果有很多用户都使用了同样的操作,那么产生的垃圾数量就相当可观了。

字符串使用原则

  1. 字符串使用就采用直接赋值

  2. 字符串比较就使用equals()实现

  3. 字符串不要改变太多,防止产生过多垃圾空间

  • 字符与字符串  String <-> char[]

            1. 字符数组 char[]-> String

                功能:将字符数组中所有内容变为字符串

                构造函数为:public String ( char[] value1 ) ;

                功能:将部分字符数组中的内容变为字符串

                构造函数为:public String ( char[] value1, int offset, int count ) ;

            2. String -> char

                功能:将字符串按照索引转为单个字符

                普通函数:public char charAt ( int index ) ;

                如果使用charAt()方法超出了字符串长度,则会产生StringIndexOutOfBoundsException异常

            3. String -> char[]     *** 重点 ***

                功能:将字符串转为字符数组

                普通函数:public char[] toCharArray( ) ;

范例:


  
  
  1. public class Test{
  2. public static void main(String[] args){
  3. String str = "helloworld" ;
  4. // 将字符串变为字符数组
  5. char[] data = str.toCharArray() ;
  6. for ( int i = 0; i < data.length; i++) {
  7. data[i] -= 32 ;
  8. System.out.print(data[i]+ "、");
  9. }
  10. // 字符数组转为字符串
  11. System.out.println( new String(data)); // 全部转换
  12. System.out.println( new String(data, 5, 5)); // 部分转换
  13. }
  14. }
  15. //输出
  16. //H、E、L、L、O、W、O、R、L、D、HELLOWORLD
  17. //WORLD

面试题:判断给定字符串是否由数字组成?  *** 重要 *** 


  
  
  1. public class Test{
  2. public static void main (String[] args){
  3. String str= "123";
  4. boolean a=MyAdjust(str);
  5. if(a== true){
  6. System.out.println( "字符串是由数字组成!");
  7. }
  8. else{
  9. System.out.println( "字符串中含有非数字成员!");
  10. }
  11. }
  12. public static boolean MyAdjust(String str){
  13. //将字符串转换为字符串数组
  14. char[] data=str.toCharArray();
  15. for( int i= 0;i<data.length;i++){
  16. if(data[i]< '0'||data[i]> '9'){
  17. return false;
  18. }
  19. }
  20. return true;
  21. }
  22. }
  • 字节与字符串    

            功能:字节数组转为字符串   byte[]  ->  String

            String构造方法:public String(byte[] bytes)

            功能:字符串转为字节数组   String  ->  byte[]   *** 非常重要 ***

            String普通方法:public byte[] getBytes(String charset);按照指定编码转为字节数组

            乱码的产生(编解码不一致,顺序不一致)

范例:


  
  
  1. public class Test {
  2. public static void main(String[] args) {
  3. String str = "helloword";
  4. byte[] data = str.getBytes();
  5. for ( int i = 0; i < data.length; i++) {
  6. data[i] -= 32;
  7. System.out.print(data[i]+ " ,");
  8. }
  9. System.out.println( new String(data));
  10. }
  11. }
  12. //编译结果如下:
  13. //72 ,69 ,76 ,76 ,79 ,87 ,79 ,82 ,68 ,HELLOWORD
  • 字符串比较

            不区分大小写的比较方法  ( 比如输入验证码 )

            public boolean equalsIgnoreCase(String anotherString)

范例:


  
  
  1. public class Test {
  2. public static void main(String[] args) {
  3. String str1= "helloword";
  4. String str2= "HELLOWORD";
  5. System.out.println(str1.equals(str2));
  6. System.out.println(str1.equalsIgnoreCase(str2));
  7. }
  8. }
  9. //编译结果如下:
  10. //false
  11. //true
  •  比较两个字符串大小关系   *** 重要 ***

            public int compareTo(String anotherString) ( 只需要比到第一个不同的字符即可 )

            1. >0 : 表示本字符串大于目标字符串

            2. =0 : 表示两者相等

            3. <0 : 表示本字符串小于目标字符串

范例:


  
  
  1. public class Test {
  2. public static void main(String[] args) {
  3. System.out.println( "A".compareTo( "a"));
  4. System.out.println( "a".compareTo( "A"));
  5. System.out.println( "A".compareTo( "A"));
  6. System.out.println( "AB".compareTo( "AC"));
  7. System.out.println( "代".compareTo( "李"));
  8. }
  9. }
  10. //编译结果如下:
  11. //-32
  12. //32
  13. //0
  14. //1
  15. //-6251
  • 字符串查找

            从一个完整的字符串当中判断一个字符串是否存在   ***  重要  ***

            public Boolean contains(Sting str);

范例:


  
  
  1. public class Test {
  2. public static void main(String[] args) {
  3. String str= "Helloworld";
  4. System. out.println(str.contains( "world"));
  5. }
  6. }
  7. //编译结果如下
  8. //true

            判断是否以指定字符串开头

            public boolean startWith(String prefix)

            public boolean startWith(String prefix,int toffset)toffset(偏移量)

            判断是否以指定字符串结尾

            public boolean endsWith(String suffix)

范例:


  
  
  1. public class Test {
  2. public static void main(String[] args) {
  3. String str= "Helloworld";
  4. System.out.println(str.startsWith( "H"));
  5. System.out.println(str.startsWith( "l", 2));
  6. System.out.println(str.startsWith( "e"));
  7. System.out.println(str.endsWith( "d"));
  8. }
  9. }
  10. //编译结果如下:
  11. //true
  12. //true
  13. //false
  14. //true
  • 字符串替换

            public String replaceAll(String regex,String replacement)

            将目标字符串全部替换

            str.replaceAll(“l”,“_”):将str中的所有 "l" 换成  "_"

            public String replaceFirst(String regex,String replacement)(替换首个)

范例:


  
  
  1. public class Test {
  2. public static void main(String[] args) {
  3. String str= "helloworld";
  4. System.out.println(str.replaceAll( "l", "*"));
  5. System.out.println(str.replaceFirst( "l", "*"));
  6. }
  7. }
  8. //编译结果如下:
  9. //he**owor*d
  10. //he*loworld
  • 字符串拆分    ***  重要  ***

            将字符串全部拆分

            public String[] split(String regex)

            将字符串拆分成数组长度为limit的字符串数组

            public String[] split(String regex,int limit)

范例:


  
  
  1. public class Test{
  2. public static void main(String[] args){
  3. String str= "hello world hello bit and you";
  4. String[] result=str.split( " ", 2);
  5. //String[] result=str.split(" ",3);
  6. //String[] result=str.split(" ",4);
  7. //String[] result=str.split(" ",5);
  8. for(String s:result){
  9. System.out.print(s+ " , ");
  10. }
  11. }
  12. }
  13. //编译结果如下:
  14. //hello ,world hello bit and you
  15. //hello ,world, hello bit and you
  16. //hello ,world ,hello ,bit and you
  17. //hello ,world ,hello, bit, and you

            特殊字符需要转义后拆分  \\

            eg:\\.

范例:  实现多次拆分   *** 重要  ***


  
  
  1. public class Test{
  2. public static void main(String[] args){
  3. String str= "yum:21|hsd:176";
  4. String[] temp=str.split( "\\|");
  5. for( int i= 0;i<temp.length;i++){
  6. String name=temp[i].split( ":")[ 0];
  7. String age=temp[i].split( ":")[ 1];
  8. System.out.println( "姓名为:"+name);
  9. System.out.println( "年龄为:"+age);
  10. }
  11. }
  12. }
  • 字符串截取   *** 重要 ***

            从指定索引截取到结尾

            public Srting substring (int beginIndex)

            从指定索引截部分内容  左闭右开  [  )

            public String substring(int beginIndex,int endIndex)

范例:


  
  
  1. public class Test {
  2. public static void main(String[] args) {
  3. String str= "helloworld";
  4. System.out.println(str.substring( 5));
  5. System.out.println(str.substring( 0, 5));
  6. }
  7. }
  8. //world
  9. //hello
  • 字符串其他操作方法

            去除字符串左右空格,并且保留中间空格

            public String trim() 可以与replaceAll配合使用  “   hello   world   ”

范例:


  
  
  1. public class Test {
  2. public static void main(String[] args) {
  3. String str= " hello world ";
  4. System.out.println( "["+str+ "]");
  5. System.out.println( "["+str.trim()+ "]");
  6. }
  7. }
  8. //[ hello world ]
  9. //[hello world]

            字符串转大小写(全部大小写)(两个函数只是在字母之间进行大小写转换)

            public String toUpperCase() //转大写

            public String toLowerCase() //转小写          

范例:


  
  
  1. public class Test {
  2. public static void main(String[] args) {
  3. String str= " Ig 牛逼 ";
  4. System.out.println(str.toUpperCase());
  5. System.out.println(str.toLowerCase());
  6. }
  7. }
  8. // IG 牛逼
  9. // ig 牛逼

范例:只将首字母转为大写  先截取,再转   面试题:  ***  重要  ***


  
  
  1. public class Test {
  2. public static void main(String[] args) {
  3. System.out.println(firstUpper( "dyson"));
  4. System.out.println(firstUpper( ""));
  5. System.out.println(firstUpper( "a"));
  6. }
  7. public static String firstUpper(String str) {
  8. //首先要判断str是否为空指针再接着判断str是否为空字符串
  9. //注意先后顺序
  10. if(str== null||str.isEmpty()){
  11. return str;
  12. }
  13. //由于从指定索引截部分内容为左闭右开 [ ),所以当字符串只有
  14. //一个字符时要特殊处理
  15. if(str.length()== 1){
  16. return str.toUpperCase();
  17. }
  18. //先将字符串中第一个字符截取出来并转化为大写,再将后面的字符
  19. //连接到该字符后边
  20. return str.substring( 0, 1).toUpperCase()+str.substring( 1);
  21. }
  22. }
  23. //Dyson A
  • 判断字符串是否为空字符串(“”,不判断null,空指针)  

            public boolean isEmpty()

            if(str==null | | str.isEmpty()){

                    //首先要判断str是否为空指针再接着判断str是否为空字符串

                    //注意先后顺序

            }

范例:


  
  
  1. public class Test {
  2. public static void main(String[] args) {
  3. System.out.println( "hello".isEmpty());
  4. System.out.println( "".isEmpty());
  5. System.out.println( new String().isEmpty());
  6. }
  7. }
  8. //false true true

猜你喜欢

转载自blog.csdn.net/wangliang369/article/details/83511427