前置知识:
你要学会如何将字符串转化为字符,如何将字符转为字符串
字符串转化为字符
String str = "abcdef";
char[] strChar = str.toCharArray();
for(int i :strChar){
System.out.print((char)i+" ");//需要进行强制类型转换,否则输出的是数字
}
System.out.println();
将字符转为字符串
String newStr = new String(strChar);
System.out.println("将字符数组转化为字符串"+newStr);
输入结果:
上手小练习:
将字符串中制定和的部分进行反转,比如将”a bcde f“反转为”a edcb f“
编写public static String reverse(String str,int start,int end)进行翻转
String newstr = null;
public static void main(String[] args) {
String str = "abcdef";
System.out.println("反转前字符串:" + str);
System.out.println("反转后字符串:" + reverse(str, 1, 5));
}
public static String reverse(String str, int start, int end) {
char[] strChar = str.toCharArray();
char temp = ' ';
for (int i = start, j = end; i < (start + end) / 2; i++, j--) {
temp = strChar[j];
strChar[j] = strChar[i];
strChar[i] = temp;
}
return new String(strChar);
}
}