import org.junit.Test;
/**
*
*
* @create 2022-03-22 16:30
*/
public class StringDemo {
/*
将一个字符串进行反转,将字符串中指定部分进行反转,
比如 "abcdefg"转换成"abfedcg"
*/
//方式一:转换为char[]
public String reverse(String str,int startIndex,int endIndex){
if(str!=null){
char[] arr=str.toCharArray();
for (int x =startIndex,y=endIndex; x < y; x++,y--) {
char temp=arr[x];
arr[x]=arr[y];
arr[y]=temp;
}
return new String(arr);
}
return null;
}
//方式二:使用String的拼接
public String reverse1(String str,int startIndex,int endIndex){
if(str!=null){
String reverseStr=str.substring(0,startIndex);
for (int i = endIndex; i >=startIndex ; i--) {
reverseStr+=str.charAt(i);
}
reverseStr+=str.substring(endIndex+1);
return reverseStr;
}
return null;
}
//方式三:使用StringBuffer/StringBuilder替换String
public StringBuilder reverse2(String str,int startIndex,int endIndex){
if(str!=null){
StringBuilder builder=new StringBuilder(str.length());
builder.append(str.substring(0,startIndex));
for(int i=endIndex;i>=startIndex;i--){
builder.append(str.charAt(i));
}
builder.append(str.substring(endIndex+1));
return builder;
}
return null;
}
@Test
public void testReverse(){
String str="abcdefg";
String reverse=reverse(str,2,5);
System.out.println(reverse);
String reverse1=reverse1(str,2,5);
System.out.println(reverse1);
StringBuilder reverse2=reverse2(str,2,5);
System.out.println(reverse2);
}
}
package exer;
import org.junit.Test;
/**
*
*
* @create 2022-03-22 17:27
*/
public class StringDemo1 {
/*
获取一个字符在另一个字符中出现的次数
以下两种解法都不严密,仅做熟悉String使用,非正确解法。
*/
public int getCount(String mainStr,String subStr){
int mainLength=mainStr.length();
int subLength=subStr.length();
int count=0;
int index=0;
if(mainLength>=subLength){
//方式一:
// while((index=mainStr.indexOf(subStr))!=-1 ){
// count++;
// mainStr=mainStr.substring(index+subLength);
// }
//方式二:对方式一的改进
while((index=mainStr.indexOf(subStr,index))!=-1){
count++;
index+=subLength;
}
return count;
}else{
return 0;
}
}
@Test
public void testGetCount(){
String mainStr="abkkcadkabkebfkaabkskab";
String subStr="ab";
int count=getCount(mainStr,subStr);
System.out.println(count);
}
}
package exer;
/**
*
*
* @create 2022-03-22 20:14
*/
public class StringDemo2 {
/*
获取两个字符串中最大相同子串
*/
//前提:两个字符串中只有一个最大相同子串
public String getMaxSameString(String str1,String str2){
if(str1!=null&str2!=null){
String maxStr=(str1.length() >= str2.length() ) ? str1 : str2;
String minStr=(str1.length() < str2.length() ) ? str1 : str2;
int length=minStr.length();
for(int i=0;i<length;i++){
for(int x=0,y=length-i;y<=length;x++,y++){
String subStr=minStr.substring(x,y);
if(maxStr.contains(subStr)){
return subStr;
}
}
}
}
return null;
}
}