public class StringChange { public static void main(String[] args) { StringChange sc = new StringChange(); String s = "abcdefg"; String s1 = sc.reverse(s,2,5); System.out.println(s1); String s2 = sc.reverse1(s,2,5); System.out.println(s2); String sub = "ab"; String str = "abkkcsdznabjcksablckkljklaab"; int count = sc.getSubCount(str,sub); System.out.println(count); } public String reverse(String str,int from,int to) { char[] c = str.toCharArray(); for (int i = from,j = to; i < j; i++,j--) { char temp = c[i]; c[i] = c[j]; c[j] = temp; } String s = new String(c); return s; } public String reverse1(String str,int from,int to) { String fiStr = str.substring(0,from); for (int i = to; i >= from; i--) { fiStr += str.charAt(i); } fiStr += str.charAt(to+1); return fiStr; } public int getSubCount(String str,String sub) { int count = 0; if(str.length() >= sub.length()) { int index = str.indexOf(sub); while (index >= 0) { count++; index = str.indexOf(sub, index + sub.length()); } } return count; } }
public class StringChange
{
public static void main(String[] args)
{
StringChange sc = new StringChange();
String s = "abcdefg";
String s1 = sc.reverse(s,2,5);
System.out.println(s1);
String s2 = sc.reverse1(s,2,5);
System.out.println(s2);
String sub = "ab";
String str = "abkkcsdznabjcksablckkljklaab";
int count = sc.getSubCount(str,sub);
System.out.println(count);
}public String reverse(String str,int from,int to)
{
char[] c = str.toCharArray();
for (int i = from,j = to; i < j; i++,j--)
{
char temp = c[i];
c[i] = c[j];
c[j] = temp;
}
String s = new String(c);
return s;
}public String reverse1(String str,int from,int to)
{
String fiStr = str.substring(0,from);
for (int i = to; i >= from; i--)
{
fiStr += str.charAt(i);
}
fiStr += str.charAt(to+1);
return fiStr;
}public int getSubCount(String str,String sub)
{
int count = 0;
if(str.length() >= sub.length())
{
int index = str.indexOf(sub);
while (index >= 0) {
count++;
index = str.indexOf(sub, index + sub.length());
}
}
return count;
}
}
JAVA的String类方法测试------JAVA
于 2023-05-09 20:10:51 首次发布