第九章 字符串String
Java中使用String类来创建一个字符串变量,字符串变量是类类型变量,是一个对象。声明字符串的语法格式如下:String s;
创建字符串:通过String类提供的构造方法可创建字符串,有以下几种方式:
(1)创建字符串对象时直接赋值,例如:
String s1 = "hello";
String s2 = new String("hello");
(2)由一个字符串创建另一个字符串,例如:
String s1 = "hello";
String s2 = new String(s1);
(3)由字符型数组创建字符串,例如:
char[] c = {‘a‘,‘b‘,‘c‘};
String s = new String(c);
获取字符串的长度:使用length()方法可以获取一个字符串的长度。
字符串的连接:除了"+"运算符,还有concat()方法,例如:
String s1 = "hello";
String s2 = "world";
String s3 = s1.concat(s2);
字符串的比较:
(1)equals方法:比较当前字符串对象的内容与参数指定的字符串对象的内容是否形同。例如:
String s1 = new String("hello");
String s2 = new String("hello");
s1.equals(2); //结果为true
比较字符串是否相等不能用“==”,当用“==”比较两个对象时,实际上是判断两个字符串是否为同一个对象。因此,即使字符串内容相同,由于是不同对象(对应引用地址不同),返回值也为false,即表达式“s1==s2”的结果为false。
euqalsIgnoreCase方法:忽略大小写比较两个字符串的内容是否相同。例如:
String s1 = new String("hello");
String s2 = new String("Hello");
s1.equalsIgnoreCase(s2); //结果为true
compareTo方法:按照字典顺序比较两个字符的大小。例如:
String s = new String("abcde");
s.compareTo("boy"); //小于0
s.compareTo("aba") //大于0
s.compareTo("abcde") //等于0
字符串的检索:
(1)indexOf(String s):从当前字符串的头开始检索字符串s,返回首次出现s的位置。如果没有则放回-1;(指定参数字符串s也可以是指定字符char a)
(2)lastIndexOf(String s):检索当前字符串,返回最后出现s的位置,如果没有则返回-1。
例如:
String str = new String("I am a good cat");
str.indexOf("a"); //返回值为2
str.lastIndexOf("a"); //返回值为13
字符串的截取:
(1)substring(int index):从当前字符串的index位置开始截取到最后得到一个子字符串。
(2)substring(int start,int end):从当前字符串的start(包括start)位置开始,截取到end(不包括end)位置得到一个子字符串。
例如:
String s1 = "helloworld";
String s2 = s1.substring(2); //s2为lloworld
String s3 = s1.substring(3,5); //s3为lo
字符串大小写转换:
(1)toLowerCase():将当前字符串的全部字符转换为小写。
(2)toUpperCase():将当前字符串的全部字符转换为大写。
例如:
String s = new String("Hello");
s.toLowerCase(); //hello
s.toUpperCase(); //HELLO
字符的替换:
(1)replace(char old, char new):将当前字符串由old指定的字符替换成由new指定的字符。
(2)replaceAll(String old, String new):将当前字符串中由old指定的字符串替换成由new指定的字符串。
(3)trim():去掉当前字符串首尾的空格
例如:
String s= "I mist sheep";
String temp = s.replace(‘t‘,‘s‘); //temp为I miss sheep
String s1 = " I am a student ";
String temp1 = s1.trim(); //temp1为I am a student
字符串转换为数值:通过调用Integer类的类方法parseInt(String s),可以将数字格式的字符串,如“1234”转化为int型数据。例如:
String s = "1234";
int x = Integer.parseInt(s); //x=1234
类似的其他数据类型也有相应的类方法将字符串转化由相应的基本类型。如parseByte()、parseShort()、parseDouble()、parseLong()。
数值转换为字符串:使用String类的valueOf方法可将数值转换为字符串。例如:
String s = String.valueOf(789.456); //s为"789.456"
StringBuffer类:用于创建和操作动态字符串,为该类对象分配的内存会自动扩展以容纳新增的文本。适用于处理可变字符串。
(1)append()方法:将给定的字符追加到当前字符串的末尾。
(2)insert()方法:在当前字符串的指定位置插入字符。
无论是append或者insert,都是在原有对象基础上操作,并没有创建新的对象。
原文:http://linyingkun.blog.51cto.com/2393912/1637751