Java学习之字符串(一)
1、字符串函数 compareTo (string) ,compareToIgnoreCase(String) 及 compareTo(object string) 来比较两个字符串,并返回字符串中第一个字母ASCII的差值。
代码如下:
String str = "Hello boy";
String anotherString = "hello girl";
Object objStr = str;
// 比较字符串
System.out.println(str.compareTo(anotherString));
System.out.println(str.compareToIgnoreCase(anotherString)); // 忽略大小写
System.out.println(str.compareTo(objStr.toString()));
2、通过字符串函数 strOrig.lastIndexOf(Stringname) 来查找子字符串 Stringname 在 strOrig 出现的位置:
代码如下:
String strOrig = "Hello boy ,Hello girl,Hello everybody!";
int lastIndex = strOrig.lastIndexOf("Hello");
if (lastIndex == -1) {
System.out.println("Hello not found");
} else {
System.out.println("最后一个Hello的位置:" + lastIndex);
}
3、通过字符串函数 substring() 函数来删除字符串中的一个字符,我们将功能封装在 removeCharAt 函数中。
代码如下:
String str = "Hello boy";
System.out.println(removeCharAt(str, 3));
public static String removeCharAt(String s, int pos) {
return s.substring(0, pos) + s.substring(pos + 1);
}
4、使用 java String 类的 replace 方法来替换字符串中的字符:
代码如下:
String str = "Hello boy";
System.out.println(str.replace('H', 'W'));
System.out.println(str.replaceFirst("He", "Wa"));
System.out.println(str.replaceAll("He", "Ha"));
5、总结代码如下:
package test;
/**
* 字符串
*
* @author 果断荒唐
*
*/
public class stringTest {
public static void main(String args[]) {
String str = "Hello boy";
String anotherString = "hello girl";
String strOrig = "Hello boy ,Hello girl,Hello everybody!";
Object objStr = str;
// 比较字符串
System.out.println("比较字符串————————————");
System.out.println(str.compareTo(anotherString));
System.out.println(str.compareToIgnoreCase(anotherString)); // 忽略大小写
System.out.println(str.compareTo(objStr.toString()));
// 查找字符串最后出现的位置
System.out.println("查找字符串最后出现的位置————————————");
int lastIndex = strOrig.lastIndexOf("Hello");
if (lastIndex == -1) {
System.out.println("Hello not found");
} else {
System.out.println("最后一个Hello的位置:" + lastIndex);
}
// 删除指定字符串
System.out.println("删除指定字符串————————————");
System.out.println(removeCharAt(str, 3));
// 替换字符串
System.out.println("替换字符串————————————");
System.out.println(str.replace('H', 'W'));
System.out.println(str.replaceFirst("He", "Wa"));
System.out.println(str.replaceAll("He", "Ha"));
}
/**
* 删除字符串
*
* @param s
* @param pos
* @return
*/
public static String removeCharAt(String s, int pos) {
return s.substring(0, pos) + s.substring(pos + 1);
}
}
6、输出结果:
