Home >Backend Development >C++ >How to Append a File Extension to a Private Class Variable in C ?
Concatenating Strings in C
In C , one common task is concatenating two strings. This can be particularly useful when handling file names or creating complex strings. While there are various methods for achieving this, using the standard library string class, std::string, offers a straightforward and efficient solution.
Question:
You have a private class variable named name[10] and wish to append the ".txt" extension to it. You prefer to store the concatenated string in a new variable. How can you accomplish this?
Answer:
Instead of resorting to char* or char arrays, leveraging the std::string class greatly simplifies the process. Here's how you can concatenate two strings in C using std::string:
std::string s = "Hello"; std::string greet = s + " World"; // Concatenation made easy!
Now, suppose you require a char const for compatibility with other functions. You can convert the std::string to char const as follows:
some_c_api(s.c_str(), s.size());
assuming the function declaration:
some_c_api(char const *input, size_t length);
For further exploration of the std::string class and its capabilities, refer to its official documentation:
The above is the detailed content of How to Append a File Extension to a Private Class Variable in C ?. For more information, please follow other related articles on the PHP Chinese website!