+ 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.

13th Oct 2017, 10:44 AM
1604064_Sharif
1604064_Sharif - avatar
6 Antworten
+ 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; }
14th Oct 2017, 5:59 AM
Babak
Babak - avatar
+ 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. @~)~~~~
14th Oct 2017, 5:20 AM
Babak
Babak - avatar
13th Oct 2017, 10:52 AM
Babak
Babak - avatar
+ 11
Probably a duplicate of Babaks fine codes, but here is a further example https://code.sololearn.com/clEpBDjJ60qp/?ref=app
13th Oct 2017, 11:04 AM
jay
jay - avatar
+ 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.
13th Oct 2017, 5:53 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 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?]
14th Oct 2017, 5:36 AM
1604064_Sharif
1604064_Sharif - avatar