Java string的基本用法
一,定义字符串与子串
定义
String e ="";\\空字符串
String E="Hello";
提取子串使用Substring方法:
String E="Hello";
String s=E.substring(0,4);\\s等于Hell
System.out.println(s);
二,字符串拼接
JAVA语言允许使用“+”连接两个字符串,相当于重新定义一个字符串,并给一个新的储存地址存放该字符串例如:
String E="Hello";
String F="World";
String G=E+F;\\G=HelloWorld
System.out.println(G);
字符串拼接还可使用concat方法:
该方法的作用是进行字符串的连接,将两个字符串连接以后形成一个新的字符串。例如:
String s = “abc”;
String s1 = “def”;
String s2 = s.concat(s1);
则连接以后生成的新字符串s2的值是”abcdef”,而字符串s和s1的值不发生改变。如果需要连接多个字符串,可以使用如下方法:
String s = “abc”;
String s1 = “def”;
String s2 = “1234”;
String s3 = s.concat(s1).concat(s2);
则生成的新字符串s3的值为”abcdef1234”。
当字符串与非字符串的值拼接时,后者会被转换成字符串:
int age=13;
String w="hello"+13;\\w=Hello13
System.out.println(w);
另外字符串是不可改变的.
三,检测字符串内容是否相等
比较两个字符串内容是否相等用equals()方法:
String str1="HelloWorld";
String str2="HelloWorld";
System.out.println( str1.equals(str2));
若字符内容一致则返回true,否则返回false。注意不可使用”“来判断。
使用比较的是两个对象在内存中存储的地址是否一样。例如
String str1 = “HelloWorld”;
String str2 = new String(“HelloWorld”);
boolean b = (s == s1);
则变量b的值是false,因为str1对象对应的地址是”HelloWorld”的地址,而str2使用new关键字申请新的内存,所以内存地址和str1的”Hello”的地址不一样,所以获得的值是false。