0

Lets say that I have a text file "myfile.txt" that assigned to a string variable and I want to get rid of the dot and the rest of extension file character .txt

#include <stdio.h>
#include <string>
#incldue <iostream>
    
int main() {

    std::string F = "myfile.txt";
    return 0;
}

So the output I want to achieve is "myfile". Using std::size doesn't look like it's gonna works on my case aswell, is there a way that I can construct what I wanted?

wohlstad
  • 12,661
  • 10
  • 26
  • 39
  • 3
    If these are file paths, have a look at std::filesystem. There is e.g. a method `std::filesystem::path::replace_extension` that can also remove it - see: https://stackoverflow.com/questions/6417817/easy-way-to-remove-extension-from-a-filename. – wohlstad Jul 17 '22 at 13:38

4 Answers4

5

When you're dealing with paths, using std::filesystem is helpful.

#include <filesystem>
#include <string>
#include <iostream>

int main() {
    std::string F = "myfile.txt";
    std::filesystem::path p(F);
    std::cout << p.stem();                         // prints "myfile"
}

or if you want it back as a string:

#include <string>
#include <iostream>
#include <filesystem>

int main() {
    std::string F = "myfile.txt";
    F = std::filesystem::path(F).stem().string(); 
    std::cout << F << '\n';                       // prints myfile
}

(or use replace_extension as in wohlstads answer)

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
2

Edit: Ted answer is better and cleaner for file, however I guess if you need to manipulate something down the road, this could be an option too.

like a substring?

#include <string.h>
#include <iostream>
using namespace std;
  
int main()
{
    // Take any string
    string s = "file.txt";
  
    // Find position of '.' using find() (or whatever your delimiter)
    int pos = s.find(".");
  
    // Copy substring before pos (or after)
    string sub = s.substr(0, pos);
  
    //result
    cout << "String is: " << sub;
  
    return 0;
}
1

I want to get rid of the dot and the rest of the extension file character .txt

Well here's one of many possible ways.

#include <string.h>
#include <iostream>
using namespace std;
int main() {
    string F = "myfile.txt";
    for(int i = size(F); i >= 0; i--) if (F[i] == '.') { F.resize(i); break; }
    cout<<F<<endl; // prints myfile
    return 0;
}
tanmoy
  • 1,276
  • 1
  • 10
  • 28
1

If your strings are paths (like they seem), you can use std::filesystem::path::replace_extension to replace or remove the extension in a path:

#include <filesystem>
#include <string>
#include <iostream>

int main() {
    std::string filename = "myfile.txt";
    std::filesystem::path p1{ filename };
    std::filesystem::path p2 = p1.replace_extension();
    std::cout << p2.string();
}

Output:

myfile

Note: this will keep the whole path (if given) except for the extension. If you need only the short filename - look at @TedLyngmo's answer.

wohlstad
  • 12,661
  • 10
  • 26
  • 39