标签:style blog ar java for strong sp 2014 on
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 ); } }
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); } } }
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); } }
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; } }
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); } }
JAVA学习第三十课(常用对象API)- String类:类方法练习
标签:style blog ar java for strong sp 2014 on
原文地址:http://blog.csdn.net/wjw0130/article/details/40119795