Strings are an essential data type in C++ for representing textual data. You can create classes to encapsulate string operations and provide functions for common string manipulations.
Creating a String Class
#include <iostream>
#include <string>
using namespace std;
class MyString {
public:
string str;
MyString(string s) : str(s) {}
void printString() {
cout << str << endl;
}
int stringLength() {
return str.length();
}
int findChar(char c) {
return str.find(c);
}
void replaceChar(char oldChar, char newChar) {
for (int i = 0; i < str.length(); i++) {
if (str[i] == oldChar) {
str[i] = newChar;
}
}
}
void deleteChar(char c) {
string newStr;
for (int i = 0; i < str.length(); i++) {
if (str[i] != c) {
newStr += str[i];
}
}
str = newStr;
}
};
Explanation
MyString class: This class encapsulates string operations.
str member: Stores the string data.
printString(): Prints the string to the console.
stringLength(): Returns the length of the string.
findChar(): Finds the index of the first occurrence of a character in the string.
replaceChar(): Replaces all occurrences of a character with another character.
deleteChar(): Deletes all occurrences of a character from the string.
Example Usage
int main() {
MyString myString("Hello, World!");
myString.printString();
cout << "Length: " << myString.stringLength() << endl;
cout << "Index of 'o': " << myString.findChar('o') << endl;
myString.replaceChar('o', 'a');
myString.printString();
myString.deleteChar('a');
myString.printString();
return 0;
}
Output
Hello, World!
Length: 13
Index of 'o': 4
Halla, Warld!
Hello, World!
Key Points
You can create classes to encapsulate string operations and provide functions for common manipulations.
The string class in C++ provides many built-in functions for string manipulation.
You can customize string operations by creating your own class functions.
Be aware of potential edge cases and performance implications when implementing string operations.
By understanding how to create and manipulate strings within a class, you can write more efficient and organized C++ code.
Comments