首页 > 应用开发 > Java > 夯实Java基础系列3:一文搞懂String常见面试题,从基础到实战
package com.mpp.string; public class StringDemo1 { public static void main(String[] args) { //定义一个字符串"晚来天欲雪 能饮一杯无" String str = "晚来天欲雪 能饮一杯无"; System.out.println("字符串的长度是:"+str.length()); //字符串的雪字打印输出 charAt(int index) System.out.println(str.charAt(4)); //取出子串 天欲 System.out.println(str.substring(2)); //取出从index2开始直到最后的子串,包含2 System.out.println(str.substring(2,4)); //取出index从2到4的子串,包含2不包含4 顾头不顾尾 } }
package com.mpp.string; public class StringDemo2 { public static void main(String[] args) { String str = new String("赵客缦胡缨 吴钩胡缨霜雪明"); //查找胡在字符串中第一次出现的位置 System.out.println("\"胡\"在字符串中第一次出现的位置:"+str.indexOf("胡")); //查找子串"胡缨"在字符串中第一次出现的位置 System.out.println("\"胡缨\"在字符串中第一次出现的位置"+str.indexOf("胡缨")); //查找胡在字符串中最后一次次出现的位置 System.out.println(str.lastIndexOf("胡")); //查找子串"胡缨"在字符串中最后一次出现的位置 System.out.println(str.lastIndexOf("胡缨")); //从indexof为5的位置,找第一次出现的"吴" System.out.println(str.indexOf("吴",5)); } }
package com.mpp.string; import java.io.UnsupportedEncodingException; public class StringDemo3 { public static void main(String[] args) throws UnsupportedEncodingException { //字符串和byte数组之间的相互转换 String str = new String("hhhabc银鞍照白马 飒沓如流星"); //将字符串转换为byte数组,并打印输出 byte[] arrs = str.getBytes("GBK"); for(int i=0;i){ System.out.print(arrs[i]); } //将byte数组转换成字符串 System.out.println(); String str1 = new String(arrs,"GBK"); //保持字符集的一致,否则会出现乱码 System.out.println(str1); } }
引用指向的内容和引用指向的地址
package com.mpp.string; public class StringDemo5 { public static void main(String[] args) { String str1 = "mpp"; String str2 = "mpp"; String str3 = new String("mpp"); System.out.println(str1.equals(str2)); //true 内容相同 System.out.println(str1.equals(str3)); //true 内容相同 System.out.println(str1==str2); //true 地址相同 System.out.println(str1==str3); //false 地址不同 } }
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69951287/viewspace-2661876/ ,如需转载,请注明出处,否则将追究法律责任。
注册时间:2019-10-19