2010年3月9日Java
字符串搜索
indexOf() //搜索字符或者字符串首次出现的位置
lastIndexOf() //搜索字符或字符串最后出现的位置
//成功返回下标,失败返回-1
int indexOf(int char) //搜索字符char首次出现的位置;
int lastIndexOf(int char) //搜索字符char最后一次出现的位置
int indexOf(String str) //搜索字符串String首次出现的位置
int lastIndexOf(String str) //搜索字符串String最后一次出现的位置
也可以通过下列形式指定搜索的起始位置
int indexOf(int char,int strtIndex);
int lastIndexOf(int char,int startIndex);
int indexOf(String str,startIndex);
int lastIndexOf(String str,startIndex);
其中startIndex指定了搜索开始的下标,对于index()方法,搜索从startIndex开始到字符串结束。
对于lastIndexOf()方法,搜索从startIndex开始到下标0
字符串的截取与替换
String substring(int startpoint) //获取从是她让调皮哦那天开始到字符串结束的子字符串
String substring(int start,int end) //获取从start处开始到end-1位置结束的子字符串,例如。
String tom = "I love tom";
String s = tom.substring(2.5);
s的结果为lov 子字符串不包括e
String replace(char oldChar,char newChar)获取一个用newChar替换所有的oldChar而得到新字符串
String replaceAll(String old,String new) 获取一个用指定字符串new替换原来
字符串中的old所指定的字符串而形成的新字符串
String s1 = "apple".replace('p','k');
String s2 = "apple".replaceAll("pp","kk");
s1和s2的结果都是"akkle"
字符串的修改
concat(String str)将两个字符串连接。str的内容跟在调用方法的字符串的后面
String s = "hello".concat("World!");
String s = " Hello World ".trim();
类型转换
public static int parseInt(String s);
public static Byte parseByte(String s);
public static Short parseShort(String s);
public static Long parseLong(String s);
public static Float parseFloat(String s);
public static Double parseDouble(String s);
数值转换为字符串
public static valueof(int n);
(byte n)
(long n)
(float n)
(double n)
double f = 123.4567;
String str;
str = String.valueOf(f); //将double类型数据转换成字符串数据类型
s1.toLowerCase() //将s1中大写字母变成小写字母
s1.toUpperCase() //将s2中小写字母变成大写
StringTokenizer(String s);
使用默认的分隔符,空格,多个空格看成一个,、换行符、回车符、Tab、进纸符
StringTokenizer(String s,String sign);
参数sign中的字符被作为分隔符
我们把StringTokenizer对象称为一个字符串分析器。一个分析器可以使用nextToken()方法逐个获取字符串中语言符号
hasMoreTokens()方法,则判断是否还有其他语言符号,(单词)只要字符串中还有语言符号,该方法返回true否则返回FALSE
因此可以用这个方法控制循环结构。