String类
字符串广泛应用 在 Java 编程中,在 Java 中字符串属于对象,Java 提供了 String 类来创建和操作字符串。
- 创建字符串最简单的方法:
String name="你好呀!";
编译器会使用name的值创建一个String对象, 和其它对象一样,可以使用关键字和构造方法来创建 String 对象。
String对象的方法:(用于获取有关对象的信息的方法称为访问器方法。)
public class StringTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
String name="Hello Word!";
//字符串长度
int len = name.length();
System.out.println(len);
//通过下标获取字符串对应的字符
char word=name.charAt(0);
System.out.println(word);
//字符串连接
System.out.println(name.concat("你好!"));
//字符串比较
System.out.println(name.equals("哈哈哈"));
//字符串比较,不考虑大小写
System.out.println("aa".equalsIgnoreCase("AA"));
//判断字符串是否以xx结尾 判断字符串是否以xx开头 startsWith()
System.out.println("我害怕!!".endsWith("!!"));
//返回字符串第一次出现的下标indexOf(),返回-1表示没找到 最后一次出现的位置lastindexOf()
System.out.println("大家好!我叫大明".indexOf("好"));
//根据特定的拆分字符串
String[] str;
str=name.split(" ");
System.out.println(str[1]);
//字符串转换为char[] 数组
char[] arr=name.toCharArray()
for (int i = 0; i < arr.length; i++) {
System.out.print("第"+(i+1)+"个:"+arr[i]+" ");
}
System.out.println();
//toString()返回一个字符串
System.out.println(name.toString());
//转换大小写 转小写toLowerCase() 转大写toUpperCase()
System.out.println(name.toLowerCase());
System.out.println(name.toUpperCase());
//忽略字符串前后空格 trim()
String str2=" sad ";
System.out.println(str2.trim());
}
}
注意:
2个字符串使用==比较运算符,比较的是地址值,如果使用的是equals方法,比较的是字符串内容是否相等
更多详细,参看 Java String API 文档