12--Summary of String-related exercises

Topic 1

  • Reverses the string entered by the keyboard.(There is actually a reverse method in StringBuilder to invert strings)

  • Code implementation as shown:

  • Development tips:

    Use character arrays to save the original characters and Random classes to generate random indexes.
    
  • Reference Answer:

public class Test1 {
   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       String next = scanner.next();
       System.out.println("Input string:" + next);
       String s = reverseStr(next);
       System.out.println("Reversed string:"+ s);
  }

   public static String reverseStr(String  str){
       String s = "";
       char[] chars = str.toCharArray();
       for (int i = chars.length - 1; i >= 0; i--) {
           s +=chars[i] ;
      }
       return s;
  }
}

Question 2

  • Enter QQ number on keyboard to verify the correctness of format.

     Must be 5-12 digits.
     0 cannot start.
    
  • Code implementation as shown:

  • Reference Answer:

public class Test2 {
   public static void main(String[] args) {
       //1. Keyboard input a qq number string
       Scanner sc = new Scanner(System.in);
       String qq = sc.next();
       //2. Call checkQQ (String qq) method to implement validation.
       boolean isOK = checkQQ(qq);
       //3. Print the results of validation
       System.out.println("this QQ Is the number correct:" + isOK);
  }

   /*
    * Definition method: Implementation validation within checkQQ (String qq) method
    * Specify the name of the method: checkQQ
    * Parameters for the specified method: String qq
    * Return value of specified method: boolean
    */
   public static boolean checkQQ(String qq){
       //1. Verify that the length of the string is between 5-12 bits;
       if (qq.length()<5 || qq.length()>12 ) {
           return false; //The length of the qq number indicated is incorrect
      }
       //2. Verify that the first character cannot be character 0; it can only be character'1'--'9'
       if (qq.charAt(0) == '0') {
           return false;
      }
       //3. Verify that each character in the string must be a character between the numeric characters'0'-'9'
       for (int i = 0; i < qq.length(); i++) {
           char ch = qq.charAt(i);
           //Determines whether a character is between the numeric characters'0'-'9'
           if (ch<'0' || ch>'9') {
               return false;//Explains that the qq number contains non-numeric characters
          }
      }
       //4. The above validation has passed, indicating that the qq number is correct
       return true;
  }
}

Question 3

  • String lookup.

     The keyboard enters a large string and a small string.
     Counts the number of occurrences of small strings in large strings.
    
  • Code implementation as shown:

  • Reference Answer:

public class Test3 {
   /*
    * Analyze the following requirements and implement them in code
       1.Keyboard enters a large string and a small string
       2.Count the number of occurrences of small strings in large strings
       3.Code Run Print Format:
           Please enter a large string: woaiheima,heimabutongyubaima,wulunheimahaishibaima,zhaodaogongzuojiushihaoma
           Please enter a small string: heima
           Console output: small string heima, three times in large string woaiheima,heimabutongyubaima,wulunheimahaishibaima,zhaodaogongzuojiushihaoma
    */

   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       // 1. Keyboard enters a large string and then a small string
       System.out.print("Please enter a large string:");
       String big = sc.nextLine();
       System.out.print("Please enter a small string:");
       String small = sc.nextLine();
       // 2. Count the number of occurrences of small strings in large strings
       int count = getCount(big, small);
       // 3. Code Run Print Format:
       System.out.println("Small string" + small + ",Cooccurrence in a large string" + count + "second");
  }

   /*
    * Method function: counts the number of occurrences of small strings in large strings
    * Parameter: big s represent large strings
    * Parameter: small stands for small string
    * Return value: the number of times a small string occurs in a large string
    */
   public static int getCount(String big, String small) {
       int index = 0;
       int count = 0;
       /*
        * indexOf(String str, int fromIndex)
        * This method works by starting at the fromIndex position, where the string str first appears, and returning -1 if it is not found
        */
       while ((index = big.indexOf(small, index)) != -1) {
           index++;
           count++;
      }
       return count;
  }
}

Question 4

  • Replace a string in a string.

     The keyboard enters an srcStr string and a delStr string.
     Deletes all delStr strings in the word srcStr string.
    
  • Code implementation, with some effects as shown in the diagram:

  • Reference Answer:
public class Test4 {
   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       // 1. Keyboard entry A source string is received by the string variable scrStr
       System.out.print("Please enter the source string:");
       String srcStr = sc.nextLine();
       // 2. Keyboard input a string to delete is received by the string variable delStr
       System.out.print("Please enter a string to delete:");
       String delStr = sc.nextLine();
       // 3. Delete all delStr strings in the scrStr string (the final string cannot contain delStr), require that the deleted results be printed, and delete several delStr strings
       printCount(srcStr, delStr);
  }

   //Delete all delStr strings in the scrStr string (the final string cannot contain delStr), require that the deleted results be printed, and delete several delStr strings
   private static void printCount(String srcStr, String delStr) {
       //Result after deletion
       String resultStr = srcStr.replace(delStr, "");
       //Deleted several delStr strings
       int count = (srcStr.length() - resultStr.length()) / delStr.length();

       System.out.println("Total contained in source string:"+ count +" individual "+ delStr +" ,\r\n delete"+ delStr +"The following string is: "+ resultStr);
  }
}

Topic 5

  • Generates a random decimal within 100, converts to a string that retains two decimal places, regardless of rounding.
  • Code implementation as shown:

  • Reference Answer:
public class Test5 {
   public static void main(String[] args) {
       double random = Math.random()*100;
       System.out.println("Random number:");
       System.out.println(random);
       String str = random+"";
       int index = str.indexOf(".");
       //System.out.println(index);
       String substring = str.substring(0, index + 3);
       System.out.println("Convert to:");
       System.out.println(substring);
  }
}

Sixth topic

  • Filter string.

     Defines an ArrayList collection, stored in multiple strings.
     String longer than 5, printing deleted collection.
    
  • Code implementation as shown:

  • Reference Answer:
public class Test6 {
   public static void main(String[] args) {
       ArrayList<String> list = getArrayList();
       System.out.println("Source string:");
       System.out.println(list);
       //Delete elements longer than 5 in the collection
       delStrsFromList01(list);
       System.out.println("After deletion:");
       System.out.println(list);
  }

   //Returns the Array List collection that stores multiple strings
   private static ArrayList<String> getArrayList() {
       ArrayList<String> list = new ArrayList<>();
       list.add("bca");
       list.add("dadfa");
       list.add("dddaaa");
       list.add("How do you do");
       list.add("I am coming,What are you doing?");
       list.add("Don't run");
       return list;
  }

   //Delete all strings longer than 5 in the list collection
   private static void delStrsFromList01(ArrayList<String> list) {
       //Create ArrayList Collection Object
       ArrayList<String> newList =  new ArrayList<String>();
       //Traversing through original collection objects
       for(int i = 0;i<list.size();i++) {
           //Get the current element
           String str = list.get(i);
           //If the length of str is greater than or equal to 5
           if(str.length()>5) {
               newList.add(str);//Add str to new collection
          }
      }
       //Traverse New Collection
       for(Object str : newList) {
           //Because the element in the new collection is the element to be deleted
           list.remove(str);
      }
  }
}

Topic 7

  • Judges the palindrome string.If a string, read forward-backward and read backward-forward, is a string called a palindrome string, such as mom, dad, noon.
  • Code implementation as shown:
  • Reference Answer:
public class Test7 {
   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       String next = scanner.next();
       boolean p = isP(next);
       System.out.println(
               "Palindrome number:" + p
      );
  }

   public static boolean isP(String str) {
       int start = 0;
       int end = str.length() - 1;
       while (start < end) {
           if (str.charAt(start) != str.charAt(end)) {
               return false;
          }
           start++;
           end--;
      }
       return true;
  }
}

Question 8

  • Verify that the password is valid.

     Must be at least 8 characters.
     Must have at least 2 uppercase characters.
     Must only have letters and numbers.
    
  • Code implementation as shown:

  • Reference Answer:

public class Test8 {
   public static void main(String[] args) {
       String s = "qweRY123";
       System.out.println(s+" Is the password legal:"+isV(s));
  }

   public static boolean  isV(String pwd){
       if (pwd.length()<8){
           return false;
      }

       int countA = 0;
       char[] chars = pwd.toCharArray();
       for (int i = 0; i < chars.length; i++) {
           char ch  = chars[i];
           // 2 uppercase characters
           if (ch >='A' && ch<='Z'){
               countA++;
          }

           // Alphanumeric
           if ((ch < '0'|| ch>'9') && (ch < 'A'|| ch>'Z')&&(ch < 'a'|| ch>'z')) {

               return false;
          }
      }
       if (countA < 2) {
           return false;
      }
       return true;
  }
}

Item 9

  • Simulate user login.

     Define a user class with properties of user name and password.
     Use collections to store multiple user objects.
     Enter user and password, compare user information, match successful login, otherwise login fails.
     When the login fails, when the user name is incorrect, it prompts that the user is not present.
     When the login fails, when the password is wrong, the password is prompted for error.
    
  • Code implementation as shown:

  • Reference Answer:

public class Test10 {
   static ArrayList<User> list = new ArrayList<>();
   static {
       list.add(new User("jack", "1234"));
       list.add(new User("rose", "5678"));
       list.add(new User("tom", "0000"));
       for (int i = 0; i < list.size(); i++) {
          list.get(i).show();
      }
  }
   public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       System.out.println("enter one user name");
       String username = sc.nextLine();
       System.out.println("Please input a password");
       String password = sc.nextLine();
       User  u = new User(username,password);
       String login = login(u);
       System.out.println("Logon Results:"+login);
  }

   public static String login(User  user){
      String msg  = "";
       String n = user.getUsername();
       String p = user.getPwd();
       for (int i = 0; i < list.size(); i++) {
           User u  = list.get(i);
           String name = u.getUsername();
           String pwd = u.getPwd();
           if(name.equals(n)) {
               if (pwd.equals(p)) {
                   return "Login Successful";
              }else {
                 // Password error
                  return  "Password error";
              }
          }else{
               msg = "user name does not exist"; //User name mismatch
             continue;
          }
      }
       return msg ;
  }
}

class User{
   private String username;
   private String pwd;

   public User() {
  }

   public User(String username, String pwd) {
       this.username = username;
       this.pwd = pwd;
  }

   public String getUsername() {
       return username;
  }

   public void setUsername(String username) {
       this.username = username;
  }

   public String getPwd() {
       return pwd;
  }

   public void setPwd(String pwd) {
       this.pwd = pwd;
  }

   public void show() {
       System.out.println(username+"-"+pwd);
  }
}

Topic 10

  • Briefly describes the differences between StringBuilder and String classes.

      Answer: The object content of the String class cannot be changed, so whenever a string is stitched,
     	 Always creates a new object in memory, so often changes the string of contents
     	 String is best not used because each object generated has an impact on system performance.
     	 
         StringBuilder, also known as variable character sequences, is a new class added to JDK5.0.
         It is a String-like string buffer that can be changed by some method calls
         Change the length and content of the sequence.That is, it is a container that can hold many characters
         String, and can perform various operations on the string.It has a number inside
         Groups are used to store string content and, when splicing strings, add new ones directly to the array
         Content, StringBuilder automatically maintains array extensions.
    

Question 11

  • String +=and StringBuilder append methods were used to make 100,000 stitches of strings, and the time spent stitching 100,000 strings and stitching 100,000 strings was calculated and printed.
public class StringBuilder01 {

    public static void main(String[] args) {

        //Use System's currentTimeMillis() method to get the millisecond value of the current operating system, start time for program execution, and receive with the start variable

        long start = System.currentTimeMillis();

        //Code that needs to test execution performance

        //testString(); //Time consumed: 29295 MS

        testStringBuilder();//Time consumed: 6ms

        //Use System's currentTimeMillis() method to get the millisecond value of the current operating system, the end time of program execution, and receive with the end variable

        long end = System.currentTimeMillis();

        //Calculates the time spent on code execution end - start, and the time spent on output code execution

        System.out.println("The time spent is:"+(end-start));

    }


    //Write a static method: testString(), in which

    public static void  testString(){

        //Define a string str with arbitrary content

        String str = "hello";

        //Write a loop 100,000 for loops, and write in the loop

        for(int i = 0; i<100000;i++){

      //STR +="random content"; do not write str +=(str+"xxx") here as this will cause heap memory overflow errors.

            str += "world";

        }

    }

    //Write a static method: testStringBuilder(), in the method

    public static void testStringBuilder(){

        //Create a StringBuilder object sb with the same initial content as the string in testString()

        StringBuilder sb = new StringBuilder("hello");

        //Write a loop 100,000 for loops, and write in the loop

        for(int i = 0; i<100000;i++){

            //callSb.append() method, the content passed in is the same as that after the testString() method +=

            sb.append("world");

        }

        //Loop End CallSb.toString() Method converted to string

        String newStr = sb.toString();

    }

}

Title 12

  • Analyze the following requirements and implement them in code:

    (1) Define the number string array {"010", "3223", "666", "7890987", "123123"};
    (2) Determine whether the number strings in the number string array are symmetrical (the first and last digits are equal, the second and last digits are equal, and so on) and output them one by one;
    (3) For example: 010 is symmetric, 3223 is symmetric, 123123 is not symmetric;
    (4) Final print the number of symmetric strings in the array.
    

Note: reverse() can be used to judge symmetry, replacing this character sequence with its inverted form.
‚Äč

public class StringBuilderTest02 {
    public static void main(String[] args) throws IOException {
        //Define an array of numeric strings
        String[] str = {"010","3223","666","7890987","123123"};
        SBTest(str);
    }

    public static void SBTest(String[] str) {
        int count = 0;
        //Traversing through defined string arrays
        for (String string : str) {
            //Create StringBuilder Object
            StringBuilder sb = new StringBuilder(string);
            //Call the reverse() method, invert the traversed number, and then use the equals() method to compare if it is the same as the original number
            if (sb.reverse().toString().equals(string)) {
                count++;
                System.out.println(string + "Symmetrical");
            }
        }
        System.out.println("Total" + count);
    }

Question 13

  • Analyze the following requirements and implement them in code:

           (1) Print a three-digit number consisting of 7, 8 and 9 digits, requiring that any two digits in the three-digit number cannot be the same;
           (2) The last three digits in the print format are separated by spaces, such as 789 798 879 897 978 987.
    

Note: StringBuilder is required to complete

public class StringBuilderTest03 {

    public static void main(String[] args) throws IOException, Exception {

        SBTest();

    }


    public static void SBTest() {

        //Define strings of 7, 8, 9

        String s = "789";

        //Create StringBuilder Object

        StringBuilder sb = new StringBuilder();

        //String traversal using nested for loop

        for (int i = 0; i < 3; i++) {

            //Traverse through the string s, adding the characters to StringBuilder in turn, to make up an element

            for (int j = 0; j < s.length(); j++) {

                sb.append(s.charAt(j));

            }

            //When elements within StringBuilder are one and two, spaces are required to separate the elements

            if (i != 2) {

                sb.append(" ");

            }

            //Cut the first element of string s, add it to the end of the string, and make up a new string

            s = s.substring(1).concat(s.substring(0, 1));

        }

        // Reverse the elements in StringBuilder to make a new number

        s = sb.toString() + " " + sb.reverse().toString();

        System.out.println(s);

    }

}
 

Posted on Mon, 15 Jun 2020 21:56:24 -0400 by harkly