String类
####1. 字符串的反转
题目描述:将一个字符串反转。将字符串中指定部分进行反转。比如“abcdefg”反转为“abfedcg”
package java.atguigu.String;
public class ReverseString {
//使用String的拼接
public String Reverse(String str, int beginIndex, int endIndex){//左闭右开
//第一部分
String reverse = str.substring(0, beginIndex);
//第二部分
for(int i = endIndex; i >= beginIndex; i--){
reverse += str.charAt(i);
}
//第三部分
reverse += str.substring(endIndex);//从endIndex开始,一直到结束
return reverse;
}
public static void main(String[] args){
String str = "abcdefg";
ReverseString rev = new ReverseString();
String reverse = rev.Reverse(str, 2, 6);
System.out.println(reverse);
}
}
Error: A JNI error has occurred, please check your installation and try again
解决:包名中出现了java,与java自带的包冲突了,将java换成com即可
2. 判断子字符串在大字符串中出现的次数
public class indexof {
public int getCount(String str, String mainStr){
int count = 0;
int mainStrLen = mainStr.length();
int strLen = str.length();
int index = 0;
/*方法一
if(mainStrLen >= strLen) {
while ((index = mainStr.indexOf(str)) != -1) {
count++;
mainStr = mainStr.substring(index + strLen); //截取主字符串:从出现的位置后面一个开始(即beginIndex + len)一直到结束
}
return count;
}
return 0;
}*/
//方法二:对方法一的改进
if(mainStrLen >= strLen) {
while ((index = mainStr.indexOf(str, index)) != -1) {
count++;
index += strLen;
}
return count;
}
else
return 0;
}
public static void main(String[] args){
String mainStr = "abcdabzxabcdab";
String str = "ab";
indexof in = new indexof();
int count = in.getCount(str, mainStr);
System.out.println(count);
}
}