Java String类
String对象一旦创建,那么他的值就不可改变,可以使用StringBuffer&StringBuilder类
字符串长度
String s = 'www'
s.length()
链接字符串
string= "www"+"aaa"
string.concat(string2)
格式化字符串输出
System.out.printf("浮点型变量的值为 " +
"%f, 整型变量的值为 " +
" %d, 字符串变量的值为 " +
"is %s", floatVar, intVar, stringVar);
String fs;
fs = String.format("浮点型变量的值为 " +
"%f, 整型变量的值为 " +
" %d, 字符串变量的值为 " +
" %s", floatVar, intVar, stringVar);
String方法
1、char charAt(int index):返回指定索引处的char值
String ss = "this is www"
ss.charAt(2)//i
2、compareTo():比较俩个字符串,按位相减
俩个字符串相等为0
俩个字符串长度相等,字符不一样返回相减值
字符长度不一样,返回不一样的字符个数
public static void main(String args[]) {
String str1 = "Strings";
String str2 = "Strings";
String str3 = "Strings123";
int result = str1.compareTo( str2 );
System.out.println(result);//0
result = str2.compareTo( str3 );
System.out.println(result);//-3
result = str3.compareTo( str1 );
System.out.println(result);//3
3、contentEquals():比较字符串是否相等
String str1 = "String1";
String str2 = "String2";
StringBuffer str3 = new StringBuffer( "String1");
boolean result = str1.contentEquals( str3 );
System.out.println(result);//true
result = str2.contentEquals( str3 );
System.out.println(result);//false
4、copyValueOf():复制字符串,可以指定开始和结束位置
char[] Str1 = {'h', 'e', 'l', 'l', 'o', ' ', 'r', 'u', 'n', 'o', 'o', 'b'};
String Str2 = "";
Str2 = Str2.copyValueOf( Str1 );
System.out.println("返回结果:" + Str2);
Str2 = Str2.copyValueOf( Str1, 2, 6 );//从2到6截取
System.out.println("返回结果:" + Str2);
5、endsWith():用于测试字符串是否以指定的后缀结束,返回true/false
System.out.print(str2.endsWith("lo"));
6、equals():判断字符串是否相等,返回值为True/False
7、equalsIgnoreCase():判断字符串是否相等返回值为boolean
8、getChars():将字符从字符串复制到目标字符串,mei
String Str1 = new String("www.runoob.com");
char[] Str2 = new char[6];
Str1.getChars(4, 10, Str2, 0);
System.out.println(Str2 );
9、hashCode():返回字符串的哈希码
String Str = new String("www.runoob.com");
System.out.println("字符串的哈希码为 :" + Str.hashCode() );
10、indexOf(str,index):返回字符串第一次出现的位置,可以指定其实位置
11、lastIndexOf(str,index):返回指定字符在此字符串最后一次出现的位置
12、matches(String regex):正则匹配,返回true/false
String str1= "this is my web";
System.out.println(str1.matches("(.*)is(.*)"));
13、replace():替换指定字符
System.out.println(str1.matches("(.*)is(.*)"));
System.out.print(str1.replace('i', 'a'));
14、replaceAll():替换指定字符串
String str1= "this is my web";
System.out.print(str1.replaceAll("is", "are"));
15、replaceFirst():替换第一个匹配到的字符串
16、split():分割字符串
System.out.println("- 分隔符设置分割份数返回值 :" );
for (String retval: str.split("-", 2)){
System.out.println(retval);
}
17、startsWith(string,index):是否以指定字符串开头
18、subSequence(start,end):截取一个新的字符序列
System.out.println(Str.subSequence(4, 10) );
19、substring():返回一个子字符串
20、toCharArray():将一个字符串转换为字符数组
System.out.println( Str.toCharArray() );
21、toLowerCase():转换为小写,toUpperCase():转换为大写
22、trim():去除前后空格
23、ValueOf():返回某种类型的字符串类型