String中:
获取字符串中的一部分
String substring(begin);从指定位置begin开始到结尾
String substring(begin,end);包含头,不包含尾
StringBufer和String的substring()方法一样:
String subString(int start,int end);
String subString(int start);
举例如下:将 "abcdefg"变成"abfedcg":
package com.lzq.stringdemo;
public class Exercise2 {
public static void main(String[] args) {
String str = "abcdefg";
System.out.println(str);
System.out.println(stringReverse(str,2,5));
}
public static String stringReverse(String str,int start , int end){
String s = str.substring(start, end+1);
String s2 = str.substring(0,start);
String s3 = str.substring(end+1);
StringBuffer buffer = new StringBuffer(s);
StringBuffer buffer2 = new StringBuffer(s2);
StringBuffer buffer3 = new StringBuffer(s3);
buffer.reverse();
buffer2.append(buffer).append(buffer3);
return buffer2.toString();
}
} |