This is the 19th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021

Like it and see. Make it a habit. Wechat search [a coding] follow this programmer who is struggling in the Internet.

This article is included in the technical expert training, which contains my learning route, series of articles, interview question bank, self-study materials, e-books, etc. Welcome to star ⭐ ️

Topic describes

Difficulty: Easy

Existing file path=”c:\ myfile\ 2021\ yitiao.txt”;

Ask to print the file name and change the suffix to a. Java file.

Such as:

yitiao.txt
yitiao.java
Copy the code

knowledge

  • String lookup
  • String interception
  • String substitution

Their thinking

1. Find the coordinates of the specified string

Observing the path, it is not difficult to find that the file name is located after \\, we need to determine the coordinates of \\, and then do string interception.

To get coordinates, you can use indeOf(), but the tricky thing is that \\ has more than one, so you need to use lastIndexOf(“\\”).

2. String interception

If you have coordinates, just use substring() to intercept them, and don’t forget coordinates +1.

3. String replacement

Java has replace and replaceAll to replace strings.

Code implementation

/** * Changes the file extension -- replaces the string */
public class question_13 {
    public static void main(String[] args) {
        String path="c:\\myfile\\2021\\yitiao.txt";
        int index=path.lastIndexOf("\ \");
        String fileName=path.substring(index+1);
        String newName=fileName.replaceAll(".txt".".java"); System.out.println(path); System.out.println(fileName); System.out.println(newName); }}Copy the code

The output

Expand the summary

On the string operation whether algorithm or later work, the application is very much, must be skilled in the use of string methods.

The last

One foot is difficult to go, one hand is difficult to sing, a person’s power is limited after all, a person’s journey is doomed to be lonely. When you set a good plan, with full of blood ready to set out, must find a partner, and Tang’s monk to the West, the master and his disciples four people united as one to pass the ninety-eight difficult. So,

If you want to learn Java well

Want to go to company

Want to get high salary

Want to have a group of like-minded partners

Please join the technical exchange