intern方法
public class Main { public static void main(String[] args) { String str1 = new String("asd"); String str2 = str1.intern();/* 字符串常量池中有,就返回字符串,没有就创建 */ System.out.println(str2); System.out.println( str1 == str2 ); } }
练习1:字符串数组排序
import java.util.Scanner; /* * 给定一个字符串数组,按字典序升序排序 */ public class Main { public static void main(String[] args) { stringsort(); } public static void stringsort() { String[] str = new String[10]; Scanner in = new Scanner(System.in); for (int i = 0; i < str.length; i++) { str[i] = in.nextLine(); } // System.out.println(str.length); for (int i = 0; i < str.length - 1; i++) { for (int j = 0; j < str.length - 1 - i; j++) { if (str[j].compareTo(str[j + 1]) > 0) { String t = str[j]; str[j] = str[j + 1]; str[j + 1] = t; } } } for (String iString : str) { System.out.println(iString); } } }
练习2:统计子串在母串中出现的次数
indexOf的应用,记录当前出现的下标A,然后再从A+子串长度继续下后indexOf,利用循环可实现本功能
import java.util.Scanner; /* * 一个子串在字符串中出现的次数 */ public class Main { public static void main(String[] args) { count(); } public static void count() { String str = "abcdefabcghiabcsdabchzabc"; int num = 0,wz = 0; for (int i = 0; i < str.length(); i++) { int t = str.indexOf("abc",wz); if(t!=-1) { wz = t+"abc".length(); num++; } else break; } System.out.println(num); } }
练习3:两个字符串的最大相同子串
import java.util.Scanner; /* * 两个字符串中的最长公共子串 */ public class Main { public static void main(String[] args) { String tString = compare(); System.out.println(tString); } public static String compare() { String str1 = "vbabcdefgsdfg"; String str2 = "asdabcdefgdf"; int Mlen = str1.length(); int Zlen = str2.length(); int len = (Mlen > Zlen) ? Zlen : Mlen; // 找较短的母串,最大的公共长度不会超过len // 公共子串可能出现在中间 for (int i = 0; i < len; i++)// 控制最大长度 { for (int j = 0, k = len - i; k <= len; k++, j++)// j控制几个满足,k控制子串最后元素下标不越界 { String sub = str2.substring(j, k); if (str1.contains(sub)) return sub; } } return null; } }
练习4:去除两端空格(模拟trim方法)
public class Main { public static void main(String[] args) { String string = " asd fs fg h "; int st = 0,en = string.length()-1; for(;st<=en && string.charAt(st)==' '; st++); for(;st<=en && string.charAt(en)==' '; en--); String sub = string.substring(st, en+1); System.out.println(sub); } }