将“I am a student.”轉換為“student. a am I”
1package test;
2import java.util.Arrays;
3public class Test7 {
4 public static void main(String[] args) {
5 String str ="I am a student.";
6 String[] sArr = str.split(" ");
7 //外層控制輪數
8 for (int i = 0; i <sArr.length; i++) {
9 //内層控制移動的元素數量
10 for (int j = 0; j < sArr.length-i-1; j++) {
11 String temp=sArr[j];
12 sArr[j]=sArr[j+1];
13 sArr[j+1]=temp;
14 }
15 }
16
17 for (String string : sArr) {
18 System.out.print(string+" ");
19 }
20 }
21}
String str1 = "abcwerthelloyuiodef";String str2 = "cvhellobnm";求兩個字元串的最大相同子串
1package test;
2public class Test8 {
3 public static void main(String[] args) {
4 String str1 = "abcwerthelloyuiodef";
5 String str2 = "cvhellobnm";
6 sop(getMaxSubString(str2,str1));
7 str2.toCharArray();
8 }
9
10 public static String getMaxSubString(String s1,String s2)
11 {
12 //求出長串、短串
13 String max = "",min = "";
14 max = (s1.length()>s2.length())?s1: s2;
15 min = (max==s1)?s2: s1;
16// sop("max="+max+"...min="+min);
17 for(int x=0; x<min.length(); x++)
18 {
19 for(int y=0,z=min.length()-x; z!=min.length()+1; y++,z++)
20 {
21 String temp = min.substring(y,z);
22 sop("("+x+","+y+","+z+")");
23 //sop(temp);
24 if(max.contains(temp))//if(s1.indexOf(temp)!=-1)
25 return temp;
26 }
27 }
28 return "";
29 }
30
31
32 public static void sop(String str)
33 {
34 System.out.println(str);
35 }
36}
單例設計模式
餓漢式:
1package test;
2public class Test9 {
3 //私有化構造方法
4 private Test9(){};
5 //私有化靜态成員變量
6 private static Test9 test = new Test9();
7 //公有的靜态方法
8 public static Test9 getTest9(){
9 return test;
10 }
11
12 public static void main(String[] args) {
13 System.out.println(Test9.getTest9()==Test9.getTest9());
14 }
15}
懶漢式:
1package test;
2 public class Test9 {
3 //私有化構造方法
4 private Test9(){};
5 //私有化靜态成員變量
6 private static Test9 test = null;
7 //公有的靜态方法
8 public static Test9 getTest9(){
9 if(test == null){
10 test = new Test9();
11 }
12 return test;
13 }
14
15 public static void main(String[] args) {
16 System.out.println(Test9.getTest9()==Test9.getTest9());
17 }
18 }
原文釋出時間為:2018-09-16
本文作者:
IT技術之道本文來自雲栖社群合作夥伴“
”,了解相關資訊可以關注“
”。