+ 1
How do I manipulate string variables in C++?
In C, strings were just character arrays. So, strings were handled the same way as any other array. Can the same be done with strings declared as string variables in C++ for manipulation? If yes, how to do it? And also what are the other methods for string manipulation in C++? If no, what are the normal methods for C++ string manipulation? Whatever the answer is, please explain in details.
6 Respuestas
+ 22
// Remove sub string from a given string
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "-----. k is the mathematician....";
string key = "the";
// find member function, searches the string for the first occurrence of the sequence specified by its arguments.
// In this case, the argument is another string called key which contains a string literal called "the". In fact, you can directly
// pass in the "the" as your argument. The position of the first character of the first match will be the return value which is stored in begin variable (12 in our case). To see the further explanation with example see the following link.
// [http://www.cplusplus.com/reference/string/string/find/]
int begin = str.find(key);
// erase member function, erases part of the string and then reduces its length.
// So, erase operation begins from 12th character 't' and move 4 characters forward till ' '.
// "-----. k is [the ]mathematician...."
// For more info about other forms of erasing see the following link.
// [http://www.cplusplus.com/reference/string/string/erase/]
str.erase(begin, 4);
cout << str;
}
+ 20
Hi Mr.Taylor,
It's laughable somehow, but I have done most of them for student's homework assignments here. For example, "How we can get the length of a string without using the language facility or something like that (inventing the wheel from scratch). But as you see, they are short and suitable for quick understanding. Thank you for your consideration. @~)~~~~
+ 16
Here are some examples of string manipulation.
[https://code.sololearn.com/cnMDVveal1I8]
[https://code.sololearn.com/cbBE9COmSHft]
[https://code.sololearn.com/c9hQM3J1Rnoh]
[https://code.sololearn.com/c0qBu1GwZRl8]
[https://code.sololearn.com/c3XYgIzLHozG]
If you had any particular question feel free and ask.
+ 11
Probably a duplicate of Babaks fine codes, but here is a further example
https://code.sololearn.com/clEpBDjJ60qp/?ref=app
+ 5
Plus, you always have the [] operator overloaded for you to use in for loops. And we even have an STL style 'at' method, for accessing, or STL style iterators to be used, if you want individual pointers.
Also, if you just need to manipulate all elements, you may even use for_each or transform, with a custom function.
+ 1
Babak, in your first code, there were lines like:
int begin=str.find(key);[what does find() do? what is stored in begin?]
str.erase(begin,4);[what are the erase() parameters? what does 4 mean here?]