String类:
1.Java程序中并没有字符串这一数据类型的使用””声明的内容都是字符串。
2.在Java中用String类的构造方法来创建字符串变量。
3.String本身属于一个系统类,除了可以利用直接赋值的形式进行对象实例化之外,同时也提供了相应的构造方法进行对象实例化。
例:public class string1 {
public static void main(String[] args) {
String str = new String(“123456”);
System.out.println(str);
}
}
运行结果:123456
连接字符串:
- 使用“+”运算符可完成对多个字符串连接的功能。“+”运算符可以连接多个运算符并产生一个String对象。
- 字符串可同其他基本数据类型进行连接,如果将字符串同这些数据类型数据进行连接,会将这些数据直接转换成字符串。
例:public class string2 {
public static void main(String[] args) {
String a = “123”;
String b = “456”;
String c;
c = a + b;
System.out.println©;
}
}
运行结果:123456
获取字符串信息:
1.获取字符串长度:使用String类的length()方法可获取声明的字符串对象的长度,语法:str.length();其中,str为字符串对象。
例:public class string3 {
public static void main(String[] args) {
int l;
String str = “123456”;
l = str.length();
System.out.println(l);
}
}
运行结果:6
2.字符串查找:String类提供了两种查找字符串的方法,即indexOf()与lastIndexOf()方法。这两种方法都允许在字符串中搜索指定条件的字符或字符串。indexOf()方法返回的是搜索的字符或字符串首次出现的位置,lastIndexOf()方法返回的是搜索的字符或字符串最后一次出现的位置。
例:indexOf():
public class string3 {
public static void main(String[] args) {
String words = “today,monday,sunday”;
System.out.println(words.indexOf(“day”));
System.out.println(words.indexOf(“day”,5));
System.out.println(words.indexOf(“o”));
System.out.println(words.indexOf(“o”,5));
}
}
运行结果:
2
9
1
7
lastIndexOf():
public class string3 {
public static void main(String[] args) {
String words = “today,monday,sunday”;
System.out.println(words.lastIndexOf(“day”));
System.out.println(words.lastIndexOf(“day”,5));
System.out.println(words.lastIndexOf(“o”));
System.out.println(words.lastIndexOf(“o”,5));
}
}
运行结果:
16
2
7
1