创建字符的两种方法:
- 直接创建
- 通过 new 关键字创建
- 通过传入一个字符类型的数组参数
String firstName = "Allen" ;
String firstName = new String("Allen");
public static void main(String args[]){
char[] helloArray = { 'r', 'u', 'n', 'o', 'o', 'b'};
String helloString = new String(helloArray);
System.out.println( helloString );
}
获取字符串长度的方法:
字符串长度方法与数组方法调用不同,
虽然都是length但是数组的为array.length;
而字符串的为String.length();
String name = "MaYun";
name.length();
连接字符串的方法
String s1 = "Ma";
String s2 = "Yun";
s1.concat(s2); //获取结果为"MaYun"
获取指定位置字符串的方法
String firstName = "Allen" ;
firstName.charAt(0); //获取结果为A;
for(int i = 0 ; i < firstName.length(); i++){
System.out.println(firstName.charAt(i));
//遍历字符串输出完整内容: "Allen";
}
截取字符串的方法
包括开始索引位置的字符,但不包括结束索引位置的字符.
String substring(int beginIndex, int endIndex)
String s1 = "HelloWorld!"
s1.substring(0,6); //获取"Hello"
判断字符串是否为空的方法
isEmpty();
//返回 true 或 flase
判断字符串是否包含指定的字符
contains(CharSequence chars)
String s = "17538****64";
System.out.println(s.contains("17538")); //返回true
String s = "17538****64";
System.out.println(s.contains("17"+"64")); //返回fales
判断字符串的开始位置方法(indexof())
- int indexOf(String str ) 返回第一次出现的指定子字符串在此字符串中的索引。
- int indexOf(String str, int startIndex):从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。
- int lastIndexOf(String str) :返回在此字符串中最右边出现的指定子字符串的索引。
- int lastIndexOf(String str, int startIndex) :从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。
String s = "1753861**64";
System.out.println(s.indexOf("3861")); //返回字符串的索引开始位置3
s.indexOf("6",8); //从索引为8的位置开始找“6”的第一次出现的索引9
s.lastindexOf("6"); //返回最后面出现的字符索引9
s.lastindexOf("6",1); //从索引1开始找最后面出现的“6”索引为9
将字符串转换为数组的方法
String s1 = "www.baidu.com";
s1.toCharArray();
字符串大小写之间的转换方法
String s1 = "www.baidu.com";
s1.toUpperCase();
s1.toLowerCase();
拆分字符串的方法
String s1 = "cheng@long";
s1.split("@");
String [] arr = s1.split("@");
System.out.println(arr[0]); //结果为"cheng"
System.out.println(arr[1]); //结果为"long"
//这里以传入的字符为分界将字符串拆分为两个字符串。
判断字符串是否以某字符开头的方法
public class Test {
public static void main(String args[]) {
String Str = new String("www.baidu.com");
System.out.print("返回值 :" );
System.out.println(Str.startsWith("www") );
//结果为true
System.out.print("返回值 :" );
System.out.println(Str.startsWith("baidu") );
//结果为false
System.out.print("返回值 :" );
System.out.println(Str.startsWith("baidu", 4) );
//结果为true
}
}