-3

I have a file "text.txt" with all lines looking like this:

directory/uninteresting1_aaa
directory/uninteresting2_bbb
directory/uninteresting3_ccc

My goal is to obtain a file with the lines looking like this:

aaa
bbb
ccc

I have printed out the lines of my text.txt file with the following code:

public void Rename(){
    FileResource rs = new FileResource("text.txt"); 
    for (String line : rs.lines()) {
        System.out.println(line);
    }

Can anybody give me a hint which method to use in order to loop over the lines to get them looking like I want to? Sorry in case this is really easy to solve but I am new to java and I couldn't find the answer in the forum. Thank you!

Lenen
  • 9

3 Answers3

0

Quick & dirty

for (String line : rs.lines()) {
    int i = line.lastIndexOf('_');
    if (i > -1)
    {
        line = line.substring(i + 1);
        //...
        System.out.println(line);
    }        
}
radoh
  • 4,554
  • 5
  • 30
  • 45
0

You could use a regex string split, like so.

String[] array = {"directory/uninteresting1_aaa",
                  "directory/uninteresting2_bbb",
                  "directory/uninteresting3_ccc"};

String regex =  "[^_]*_" ;

for(String s : array)
{
    System.out.println( Arrays.toString( s.split( regex ) ) );
}
Tom C
  • 804
  • 2
  • 11
  • 24
0

Essentially what you're looking for is a way to split a String and keep only the last part. There are countless ways to do this, some better than others depending on what the string looks like (eg String.split(), String.substring() etc). In this case you have a string in a well known format - a filename. You could identify the last underscore of the string and use split or substring at this index. Alternatively, if the filenames aren't in a format as simple as the example you could use String.replace() which allows you to match parts of the string to a pattern, which can be done with regex making it extremely powerful, but fairly slow. I would recommend that you look at these options (there are many more too) and decide which would be best for your situation.

ewanc
  • 1,284
  • 1
  • 12
  • 23