Use of the substring() and lastIndexOf() methods of the String class

Two methods

  • Substring () : Returns a substring of a string;

Grammar:

Public String substring(int endIndex, int endIndex) public String substring(int endIndex, int endIndex, int endIndex) The index starts at 0; EndIndex -- to end the index (excluding);
  • LastIndexOf () : Returns the index at the last occurrence of the specified character/string in the string, or -1 if there is no such character in the string;

Grammar:

public int lastIndexOf(int ch) public int lastIndexOf(int ch, Int fromIndex) public int lastIndexOf(String STR, int fromIndex) public int lastIndexOf(String STR, int fromIndex) FromIndex - Index position from which to start the search, with index starting value 0; STR -- the substring to search for;

Take a chestnut

Scenario: Get the suffix name of the file when uploading the file;

Description: When a file is sent from the front end (.txt,.png,.jpg, etc.), we usually rename the file in the background in order to prevent the rename, but to ensure that the type of the file is not changed, so we need to get the suffix of the file name first, and then rename the file through the stitching operation;

String filename = file.getOriginalFileName (); String suffix = filename.substring(filename.lastIndexOf(".") + 1); String NICKNAME = System.currentTimeMillis() + "." + suffix;

Refer to the link: https://www.runoob.com/java/j… https://www.runoob.com/java/j…