Advertisement
Askja

Untitled

Aug 16th, 2022
1,014
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.30 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3. #include <cstdlib>
  4.  
  5. using namespace std;
  6.  
  7. int getRightPos(char *string, char search) {
  8.     for (int k = strlen(string); k >= 0; k--) {
  9.         if (string[k] == search) {
  10.             return k;
  11.         }
  12.     }
  13.  
  14.     return -1;
  15. }
  16.  
  17. char *getExtension(char *path) {
  18.     int pos = getRightPos(path, '.');
  19.  
  20.     if (pos != -1) {
  21.         char *ext = new char[strlen(path) - pos];
  22.  
  23.         for (size_t k = 0, j = pos; k <= strlen(ext); k++, j++) {
  24.             ext[k] = path[j];
  25.         }
  26.  
  27.         return ext;
  28.     }
  29.  
  30.     return nullptr;
  31. }
  32.  
  33. char *replaceExtension(char *oldPath, char *newExt) {
  34.     int pos = getRightPos(oldPath, '.');
  35.  
  36.     if (pos != -1) {
  37.         const int newSize = pos + strlen(newExt) + 1;
  38.  
  39.         char *newPath = new char[newSize];
  40.  
  41.         for (int k = 0, j = 0; k < newSize; k++) {
  42.             if (k >= pos) {
  43.                 newPath[k] = newExt[j++];
  44.             } else {
  45.                 newPath[k] = oldPath[k];
  46.             }
  47.         }
  48.  
  49.         return newPath;
  50.     }
  51.  
  52.     return oldPath;
  53. }
  54.  
  55. int main() {
  56.     char path[210] = "D:\\Pathname\\Superpuper\\test.ltx";
  57.  
  58.     cout << getRightPos(path, '.') << endl;
  59.     cout << getExtension(path) << endl;
  60.     cout << replaceExtension(path, ".jpeg");
  61.  
  62.     return 0;
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement