Extract file extension: Difference between revisions

From Rosetta Code
Content added Content deleted
(Rewritten.)
(J)
Line 50: Line 50:
return result;
return result;
}
}
</lang>

=={{header|J}}==

Implementation:

<lang J>require'regex'
ext=: '[.][a-zA-Z0-9]+$'&rxmatch ;@rxfrom ]</lang>

Task examples:

<lang J> ext 'picture.jpg'
.jpg
ext 'http://mywebsite.com/picture/image.png'
.png
ext 'myuniquefile.longextension'
.longextension
ext 'IAmAFileWithoutExtension'

ext '/path/to.my/file'

ext 'file.odd_one'
</lang>
</lang>

Revision as of 19:21, 4 May 2015

Extract file extension is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Write a program that takes one string argument representing the path to a file and returns the files extension, or the null string if the file path has no extension. An extension appears after the last period in the file name and consists of one or more letters or numbers.

Show here the action of your routine on the following examples:

  1. picture.jpg returns .jpg
  2. http://mywebsite.com/picture/image.png returns .png
  3. myuniquefile.longextension returns .longextension
  4. IAmAFileWithoutExtension returns an empty string ""
  5. /path/to.my/file returns an empty string as the period is in the directory name rather than the file
  6. file.odd_one returns an empty string as an extension (by this definition), cannot contain an underscore.


C#

<lang C#> public static string ExtractExtension(string str) {

           string s = str;
           string temp = "";
           string result = "";
           bool isDotFound = false;
           for (int i = s.Length -1; i >= 0; i--)
           {
               if(s[i].Equals('.'))
               {
                   temp += s[i];
                   isDotFound = true;
                   break;
               }
               else
               {
                   temp += s[i];
               }
           }
           if(!isDotFound)
           {
               result = "";
           }
           else
           {
               for (int j = temp.Length - 1; j >= 0; j--)
               {
                   result += temp[j];
               }
           }
           return result;

} </lang>

J

Implementation:

<lang J>require'regex' ext=: '[.][a-zA-Z0-9]+$'&rxmatch ;@rxfrom ]</lang>

Task examples:

<lang J> ext 'picture.jpg' .jpg

  ext 'http://mywebsite.com/picture/image.png'

.png

  ext 'myuniquefile.longextension'

.longextension

  ext 'IAmAFileWithoutExtension'
  ext '/path/to.my/file'
  ext 'file.odd_one'

</lang>