课后作业2-字符串

动手动脑之String.equals()方法、整理String类的Length()、charAt()、 getChars()、replace()、 toUpperCase()、 toLowerCase()、trim()、toCharArray()使用说明

1.动手动脑之String.equals()方法

String类型当比较不同对象内容是否相同时,应该用equals,因为“==”用于比较引用类型和比较基本数据类型时具有不同的功能。

1:当对象不同,内容相同,"=="返回false,equals返回true

String s1=new String(“java”);

String s2=new String(“java”);

System.out.println(s1==s2);//false

System.out.println(s1.equals(s2));//true

2:当同一对象,"=="和equals结果相同

String s1=new String(“java”);

String s2=s1;

System.out.println(s1==s2);//true

System.out.println(s1.equals(s2));//true

3:如果值不相同,对象就不相同,所以"==" 和equals结果一样

String s1=”java”;

String s2=”java”;

System.out.println(s1==s2);//true

System.out.println(s1.equals(s2));//true

2.整理String类的Length()、charAt()、 getChars()、replace()、 toUpperCase()、 toLowerCase()、trim()、toCharArray()使用说明

length():public int length()//求字符串长度

         String s=”dwfsdfwfsadf”;

         System.out.println(s.length());

charAt():public charAt(int index)//index 是字符下标,返回字符串中指定位置的字符

        String s=”Hello”;

        System.out.println(s.charAt(3));

getChars():public int getChars()//将字符从此字符串复制到目标字符数组

        String str = "abcdefghikl";

        Char[] ch = new char[8];

        str.getChars(2,5,ch,0);

replace():public int replace()//替换字符串

        String s=”\”;

        System.out.println(s.replace(“\”,”///”));

        结果///;

toUpperase():public String toUpperCase()//将字符串全部转换成大写

         System.out.println(new String(“hello”).toUpperCase());

toLowerCse():public String toLowerCase()//将字符串全部转换成小写

         System.out.println(new String(“HELLO”).toLowerCase());

trim():public String trim()

         String x=”ax  c”;

         System.out.println(x.trim());//是去两边空格的方法

toCharArray(): String x=”abcd”;// 将字符串对象中的字符转换为一个字符数组

           char myChar[]=x.toCharArray();

          System.out.println(“myChar[1]”+myChar[1]);

原文地址:https://www.cnblogs.com/liurx/p/7744056.html