/**
* String 代表不可變的CharSequence,簡稱不可變性
* @author sunwc
* @create 2023-03-25 下午 02:51
*/
public class StringTest {
private String str = new String("good");
private char[] ch = {'t','e','s','t'};
private void change(String str, char[] ch) {
str = "test ok";
ch[0] = 'b';
}
public static void main(String[] args) {
StringTest stringTest = new StringTest();
stringTest.change(stringTest.str, stringTest.ch);
System.out.println(stringTest.str); // good
System.out.println(stringTest.ch); // best
}
}
幫助理解為什麼String 是不可變的
取得兩個字串中最大相同子串。例如str1 = "abcwerthelloyuiodef", str2 = "cvhellobnm";
提示:將較短的字串在每一輪時總長度--,並在這個長度下得出不同組合,
例如 str2 = "cvhellobnm"
第一輪會變成 => cvhellobnm => str1進行比較;
第二輪會變成 cvhellobn 與 vhellobnm => str1進行比較;
第三輪會變成 cvhellob 與 vhellobn 與 hellobnm => str1進行比較;...以此類推
/**
* @author sunwc
* @create 2023-03-26 下午 01:08
*/
public class StringDemo {
@Test
public void getLongestSubString() {
String str1 = "abcwerthelloyuiodef", str2 = "cvhellobnm";
// 1.定義較長與較短字串
String maxString = str1.length() > str2.length() ? str1 : str2;
String minString = str1.length() < str2.length() ? str1 : str2;
// 2.定義較短字串長度
int minLength = minString.length();
/**
* 先假設minString = abcdefg
* 第一輪 i = 0, substring(0, minLength) => abcdefg;
* 第二輪 i = 1, substring(0, minLength - 1) => abcdef,
* substring(1, minLength) => bcdefg;
* 第三輪 i = 2, substring(0, minLength - 2) => abcde,
* substring(1, minLength -1) => bcdef,
* substring(2, minLength) => cdefg
* 以此類推......
*/
back:{
for (int i = 0; i < minLength; i++) {
for (int start = 0, end = minLength - i; end <= minLength; start++, end++) {
// 3. 取得此輪固定長度下的不同組合subString
String subString = minString.substring(start, end);
// 4. 判斷較長字串是否包含minString的substring
if (maxString.contains(subString)) {
System.out.println("找到longest substring為:" + subString);
// 直接挑出外層迴圈
break back;
}
}
}
}
}
}
輸出結果:
找到longest substring為:hello
取得一個字串在另一個字串中出現的次數,例如:取得"ab"在"abkkcadkabkebfkabkskab"中出現的次數
@Test
public void duplicateString() {
String minString = "ab";
String maxString = "abkkcadkabkebfkabkskab";
int count = 0;
for (int i = 0; i < maxString.length();) {
// 不是-1代表有找到
if (maxString.indexOf(minString) != -1) {
count++;
// startIndex後移minString.length()位
maxString = maxString.substring(i += minString.length());
} else {
// startIndex後移1位
maxString = maxString.substring(++i);
}
}
System.out.println("字串在另一個字串中出現的次數為:" + count);
}
輸出結果:
字串在另一個字串中出現的次數為:4
對字串String str1 = “abcwerthelloyuiodef"中的字符進行自然順序排序
提示
1.字串變成char array
2.對陣列排序(選擇排序、氣泡排序、Arrays.sort())
3.將排序後的陣列變成字串
@Test
public void orderStringAlphabetical() {
String str1 = "abcwerthelloyuiodef";
char[] chars = str1.toCharArray();
for (int i = 0; i < chars.length; i++) {
for (int j = i+1; j < chars.length; j++) {
if (chars[i] > chars[j]) {
// swap
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
}
}
System.out.println(chars);
}
輸出結果:
abcdeeefhilloortuwy