//String类的构造方法:
//1.作为基本数据类型,直接赋值
String a = "abc";
String a1= new String("abc"); //a和a1是两个对象,地址值不一样
String a2 = new String("abc").intern();//a和a2是同一个对象,地址值一样
System.out.println(a1==a2);
//2.利用字符数组,构造字符串对象
char[] chars = new char[]{'I','’','m','C','O','O','L'};
String s = new String(chars);
//3.含中文的需要用一致的字符集解析,否则乱码;
String b ="I'm not Cool 泫雅!";
byte[] bytes = b.getBytes("UTF-8");
String s1 = new String(bytes, Charset.forName("UTF-8"));
System.out.println(a);
System.out.println(s);
System.out.println(s1);
//格式化字符串;
String name = "Hyun";
String career = "Singer";
int age = 24;
double salary = 886699.8866;
//方法一: String.format :"%s,%s,%d,%.2f" (%是分隔符;s为String;d为double;.2f代表数字要保留的精度;变量顺序要符合前方的分割类型)
System.out.println(String.format("%s,%s,%d,%.2f", name, career, age, salary));
//方法二;MessageFormat.format;用于少数字符串已知的拼接,其坑位可以复用,比较方便
System.out.println(MessageFormat.format("{0},{1},{2},{3}", name, career, age, salary));*/
//将其他类型转化为字符串类型
Integer a=999999999;
String s = String.valueOf(a); //String.valueOf();静态方法,将其他类型军转化为字符串类型
System.out.println(s);
//字符的拼接;StringBuilder;
String[][] arr = new String[][]{{"Hyun","OH~~" },{"is singer"},{"my favorit","beauty"}};
StringBuilder builder = new StringBuilder();
for (String[] strings : arr) {
for (String string : strings) {
builder.append(string);
builder.append(",");
}
}
builder.deleteCharAt(builder.length()-1); //消除最后一个的','号
System.out.println(builder);*/
//String主体方法的使用;
String str = "you lift my feet off the ground, you spin me around";
str.getBytes("UTF-8"); //将str根据指定字符集转化为字节数组
System.out.println(str.length());
char[] chars = str.toCharArray();//将字符串转化为字符数组
System.out.println(chars);
String str2= "YOU LIFT MY FEET OFF THE GROUND, YOU SPIN ME AROUND";
System.out.println(str.equals(str2)); //内容等值比较【区分大小写】
System.out.println(str.equalsIgnoreCase(str2)); //内容等值比较【不区分大小写】
System.out.println(str.startsWith("yo")); // str是否以prefix开始,或以suffix结束,区分大小写
System.out.println(str.startsWith("YOU"));
System.out.println(str2.endsWith("AROUND"));
System.out.println(str.contains("et"));// str2是否包含midfix字符*/
//截取
String mail = " frog.464699@qq.com ";
System.out.println(mail.charAt(mail.length() - 1));
System.out.println(mail.substring(mail.indexOf('.') + 1, mail.indexOf('@'))); //截取str中从beginIndex开始(含本身)至endIndex截止(不含)的所有内容
//查找下标
System.out.println(mail.indexOf("46"));
System.out.println(mail.lastIndexOf("46"));
//分割
String[] split = mail.split("\\.|@");
for (String s : split) {
System.out.println(s);
}
boolean matches = mail.matches("\\w{4,}\\.\\w{4,}@\\w{2,}\\.(com|cn|org|com.cn)");
System.out.println(matches);
//replace
String replace = mail.replace("frog", "henry");
System.out.println(replace);
String replace1 = mail.replace(".", "&");
System.out.println(replace1);
System.out.println(mail);
//修剪
System.out.println(mail.trim());
String类型的常用用法概述
最新推荐文章于 2024-06-01 17:45:06 发布