package com.atguigu.java; import java.util.Arrays; /** * @author Suki * @creat 2022-09-18 14:58 */ public class StringExer { //第二题方法3 public String reverse1(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.toString(); } return null; } //第二题方法2 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; } public static void main(String[] args) { //第一题 String s1 = " hello , world "; String s2 = s1.trim(); System.out.println(s1); System.out.println(s2); //第二题 String s3 = "abcdefg"; char[] chars = s3.toCharArray(); for (int i = 2; i <4 ; i++) { char temp = chars [i]; chars[i] = chars[7-i]; chars[7-i] = temp; } String s4 = new String(chars); System.out.println(s4); //方法2 StringExer exer = new StringExer(); String reverseString = exer.reverse(s3, 2, 5); System.out.println(reverseString); //方法3 String reverse1 = exer.reverse1(s3, 2, 5); System.out.println(reverse1); //第三题 String s5 = "abkkcadkabkebfkabkskab"; String s6 = "ab"; int count = 0; for(;;){ int index = s5.indexOf(s6); if(index != -1){ count++; String s7 = s5.substring(index + 1); s5 = s7; }else{ break; } } System.out.println(count);//4 //第四题 String s8 ="abcwerthelloyuiodef"; String s9 ="cvhellobnm"; String s10; String s11; int index; int maxlength = 0; String maxsubString = null; for (int i = 0; i < s9.length(); i++) { s10 = s9.substring(i,s9.length()); index = s8.indexOf(s10); if(index != -1 && s10.length() > maxlength){ maxlength = s10.length(); maxsubString = s10; } for(int j=0;j <s10.length();j++){ s11 = s10.substring(0,s10.length()-j); index = s8.indexOf(s11); if(index != -1 && s11.length() > maxlength){ maxlength = s11.length(); maxsubString = s11; } } } System.out.println(maxsubString +"长度为:"+ maxlength); //第五题 String str1 = "6529533256954"; char[] arr = str1.toCharArray(); Arrays.sort(arr); String str2 = new String(arr); System.out.println(str2); } }
String类常见算法题目
于 2022-09-18 17:21:16 首次发布