suppose I am declaring a string s. Now on step can I push values in its i th index like s[i]=‘any character’. ?
About strings class
@sktg99 Yes you can do that using insert function. Refer this http://www.cplusplus.com/reference/string/string/insert/
actually the language of cplusplus.com is quite difficult to understand, is there any other source pf tutorials for this ?
I am telling you in simplified way.
Consider two strings str1 and str2. insert() is used to insert characters in string at specified position. It supports various syntaxes to facilitate same.
- To Insert str2 in str1 starting from any index say the 6th index of str1
str1.insert(6, str2); - To Insert 6 characters from index number 8 of str2 at index number 6 of str1
str1.insert(6, str2, 8, 6); - To Insert ‘x’ at position str.begin() + 5 ie.5 positions ahead from beginning
pos = str.insert(str.begin()+5,‘x’); - Insert str2.begin() + 5 , str2.end() - 6 at position str1.begin() + 6
str1.insert(str1.begin() + 6, str2.begin() + 5 , str2.end() - 6);
In these ways you can use the insert function.
Also to push or pop a character from the back similar as in vector, you can use the push_back() and pop_back() functions respectively.
- Using push_back() to insert a character at end pushes ‘s’ in this case
str.push_back(‘s’); - Using pop_back() to delete a character from end.
str.pop_back();
how can we insert at 8th index if we didnt know the size of string, that means size of string is infinite? if we are treating it like a vector, also push back and pop back will pop or push at which index from the end? we have no where defined the end of the string? is it automatically defining the end of string at some point or what?
also clarify that if we initiate a string and a character array, what is the difference in two ?
Yes to insert at a particular position, you should know the length of the string. push_back() and pop_back() is used to insert a character at the end of the string and to delete a character from end respectively.
Suppose:
string str=“CodingBlock”; //Initializing a string
str.push_back(‘s’); //this will append a character ‘s’ after the last character of CodingBlock making it CodingBlocks
str.pop_back(); // this will remove the last character ie. ‘s’ making the string CodingBlock
Note that these are STL functions of string class and they will not work on string made by character arrays.
Refer this. This might help you.