动手动脑一:查看其输出结果。如何解释这样的输出结果?从中你能总结出什么
public class StringPool {
public static void main(String args[])
{
String s0="Hello";
String s1="Hello";
String s2="He"+"llo";
System.out.println(s0==s1);//true
System.out.println(s0==s2);//true
System.out.println(new String("Hello")==new String("Hello"));//false
}
}
答案:因为字符串中,相同的变量处于相同的地址,而且“==”比较的是地址是否相同,“+”在字符串中代表的是连接。所以1、2个是正确的。而new是对对象分配空间,第三个是对两个“Hello”分配了不同的存储空间,所以两个不相等。
动手动脑二:请查看String.equals()方法的实现代码,注意学习其实现方法。
public class StringEquals {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String s1=new String("Hello");
String s2=new String("Hello");
System.out.println(s1==s2);//false
System.out.println(s1.equals(s2));//true
String s3="Hello";
String s4="Hello";
System.out.println(s3==s4);//true
System.out.println(s3.equals(s4));//true
}
}
答案:在第一部分比较的是地址的相同,所以是false第二部分是比较s1和s2的大小不是存储位置,所以相等,第三部分是直接复制对象,对象的比较是比较值的大小,所以第三和第四部分都相等。equals类型是取值,s3.equals(s4)是比较取值是否相等。
3、整理String类的Length()、charAt()、 getChars()、replace()、 toUpperCase()、 toLowerCase()、trim()、toCharArray()使用说明:
Length():计算字符串的长度;
计算字符串的长度;String s = new String(“abcdefghijklmn”);System.out.println(s.length());
charAt():获取指定位置的字符;char charAt(int index)其中的参数index为字符串参数,字符串的序数从0到length-1;例如:String s = new String(“abcdefghijklmn”);System.out.println(“s.charAt(5):”+s.charAt(5));结果为s.charAt(5):f。
getChars():获取从指定位置起的子串复制到字符串数组中;void getChars(int scrBegin,int scrEnd,char[] dst,int dstBegin);scrBegin拷贝起始的位置,scrEnd拷贝结束的位置,字符串数值dst为目标字符串数组,dstBegin为目标字符串数组的起始位置。例如:char[]s1 = {‘i’,’ ’,’l’,’o’,’v’,’e’,’ ’,’m’,’e’,’!’};
String s2 = new String (“you!”);s2.getChar(0,3,s1,7);
System.out.println(s1);
结构为:i love you!
replace():子串替换;
toUpperCase():转换为大写;
String s1=new String(“abcd”) ;String s2 = s1.toUpperCase();
toLowerCase():转换为小写;
String s1=new String(“ABCD”) ;String s2 = s1.toUpperCase();
trim():去除头尾空格;
toCharArray():将字符串转换为字符数组;
4、课后作业
设计思想:
1,先输入一段字符;
2、将字符转换为字符串;
3、进行判断是否为X、Y、Z;如果是。执行4,不是,执行5;
4、字符减23;
5、字符加3;
import javax.swing.JOptionPane;
public class StringMiMa{
public static void main(String[] args){
String s = JOptionPane.showInputDialog("请输入字符串:");
char charArray[] = s.toCharArray();//将字符串转化为字符数组
for(int i = 0;i<charArray.length;i++)
{
if(charArray[i]=='X'||charArray[i]=='Y'||charArray[i]=='Z')
charArray[i]=(char)(charArray[i]-23);
else
charArray[i] = (char)(charArray[i]+3);
}
JOptionPane.showMessageDialog(null,"加密后的字符串:"+String.valueOf(charArray));
}