您的位置:首页 > 其它

String 类常用方法

2015-09-18 22:57 411 查看
/*
* 字符串:就是由多个字符组成的一串数组
* 		  一旦被复制,就不能被改变
*
*/
public class StringDemo {
public static void main(String[] args) {
// void
String s1 = new String();
System.out.println("s1:" + s1);
System.out.println("s1.length():" + s1.length()); // 0
System.out.println("----");
// public String(byte[] bytes);
byte[] bys = { 97, 98, 99, 100, 101 };
String s2 = new String(bys);
System.out.println("s2:" + s2);
System.out.println("s2.length():" + s2.length()); // 5
System.out.println("----");
// public String (byte[] bytes,int index,int length);
String s3 = new String(bys, 0, 3);
System.out.println("s3:" + s3);
System.out.println("s3.length():" + s3.length()); // 3
System.out.println("----");
// public String(char[] value)
char[] chs = { 'a', 'b', 'c', 'd', 'e', '我', '爱', '你' };
String s4 = new String(chs);
System.out.println("s4:" + s4);
System.out.println("s4.length():" + s4.length()); // 8
System.out.println("----");
// public String(char[] value,int index,int count);
String s5 = new String(chs, 2, 6);
System.out.println("s5:" + s5);
System.out.println("s5.length():" + s5.length()); // 6
System.out.println("---");

/*
*
*/
String ss1 = "hello";
String ss2 = "beautiful";
ss1 += "world";
ss2 += ss1;
System.out.println("ss1:" + ss1);
System.out.println("ss2:" + ss2);
<span style="white-space:pre">		</span>/*
<span style="white-space:pre">		</span> * 
<span style="white-space:pre">		</span> */
<span style="white-space:pre">		</span>String ss3 = new String("hello");
<span style="white-space:pre">		</span>String ss4 = "hello";
<span style="white-space:pre">		</span>System.out.println(ss3 == ss4); //false
<span style="white-space:pre">		</span>System.out.println(ss3.equals(ss4)); //true
<span style="white-space:pre">		</span>System.out.println("----");
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>/*
<span style="white-space:pre">		</span> * 字符串变量想家:先开空间,再拼接;
<span style="white-space:pre">		</span> * 字符串常量想家,先加,再在常量池找,有就返回,否则创建;
<span style="white-space:pre">		</span> */
<span style="white-space:pre">		</span>String sss1 = "hello";
<span style="white-space:pre">		</span>String sss2 = "world";
<span style="white-space:pre">		</span>String sss3 = "helloworld";
<span style="white-space:pre">		</span>System.out.println(sss3 == sss1+sss2);  //false
<span style="white-space:pre">		</span>System.out.println(sss3.equals(sss1+sss2));  //true
<span style="white-space:pre">		</span>System.out.println(sss3 == "hello"+"world");  //true
<span style="white-space:pre">		</span>System.out.println(sss3.equals("hello"+"world"));  //true

}
}
结果:
s1:s1.length():0----s2:abcdes2.length():5----s3:abcs3.length():3----s4:abcde我爱你s4.length():8----s5:cde我爱你s5.length():6---ss1:helloworldss2:beautifulhelloworld---falsetrue---falsetruetruetrue

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: