Question:
How do I extract a character from a string that is an array?
Explained:
Normal strings
string example=("Stack Over Flow");
cout<<example[1];
The output will be:
t
What I want is to extract a letter from an array of strings example:
string str[4];
str[0]="1st";
str[1]="2nd";
str[2]="3rd";
str[3]="4th";
cout<<str[2];
will print
3rd
how could i get the "t" from the str[0]?
just by doing as follow:
str[0][2]; // third character of first string
Some more examples:
string str[4];
str[0]="1st";
str[1]="2nd";
str[2]="3rd";
str[3]="4th";
cout<<str[0][2]<<endl; // t
cout<<str[2][1]<<endl; // r
cout<<str[3][2]<<endl; // h
std::string str[4];
str[0]="1st";
str[1]="2nd";
str[2]="3rd";
str[3]="4th";
Here str is an array of std::string objects. As you know you access elements of an array with operator[]. So the first string in the array is accessed with str[0].
std::string offers operator[] as well. With it you can access characters of the string.
So lets take it step by step.
str - array
str[0] - std::string
str[0][0] - first character of the string str[0]
YOu need one more operator[] call. str[2] is using the [] of the array and returns a reference to the array element at index 2. If you want to get the second character of the first array element then you need
str[0][2]
^ ^
string |
character
Class std::string has its own overloaded operator [] that you used in the first your code snippet
string example=("Stack Over Flow");
cout<<example[1];
If you have an array of objects of type std::string then at first you need to access the desired object stored in the array using the built-in subscript operator [] of arrays as for example
string str[4];
cout << str[1];
In this code snippet expression str[1] returns string stored in the second element (with index 1) of the array. Now you can apply the overloaded operator [] of the class std::string as for example
string str[4];
cout << str[1][1];
You get 't' instead of 's' because you are printing it like this cout<<example[1];
you sohuld do it like this:
cout<<example[0][2];
Related
I'm having trouble understanding some particular behaviour of assignment in strings.
//method 1
std::string s;
s+='a' //This works perfectly
but
//method2
std::string s;
s="" + 'a';//This gives unexpected value
Why 2nd method gives unexpected value ? From what I've read string default constructor initialise string variable as empty string, if no constructor is specified. And s+='a' should be same as s=s+a. So why isn't the method 2 same as method 1?
And one more query on the same topic , if we can't initialise a string with char literal then how can we assign a char literal to it?
std::string s2='a'//gives error while compiling
whereas
std::string s2;
s2='a'//works perfect
From what I understand is we cannot initialise a string variable by char variable because string constructor needs argument of the type(const char *). Why is there not any such restriction while assigning?
For your first query ,
method 1 works perfectly cause in this method you are adding string object type and char literal .
and s+='a' , is indeed same as s=s+'a'
focus on the fact that s is string object type rather than string literal.
In the 2nd method , you are adding string literal
and char literal . Focus on the difference between the two , In first method there is string object you can add string or char literals to string object type,its one of the features provided by string object type . But you cant add simply add the literals with each other.In c++ , however "StringLiteral1" "StringLiteral2" , will result in the concatenation of the two string literals.
for 2nd query,
Initialisation is not the same as assignment , string object default constructor takes const char * to initialise . Assignment is a completely differenet story(if not,someone please do correct me ).
"" is a string literal of type const char[], and you are adding the string literal, i.e. the pointer to the first element, '\0', to another character. This will naturally give you something else then you expected.
If you want it to be the same as s += 'a', you'll need to use a std::string literal: s += ""s + 'a';. This works, as ""s is an empty std::string, and you just add another character to it.
When you write s="" + 'a'; Remember that "" is not a std::string but a const char*. And const char* doesn't have a predefined concatenation operator. That's why you are having an unexpected behavior instead of concatenation.
I need to convert a char array to string to use the string on a finite automaton, i've tried char[50]=string but it copies it indeed but has rubbish on in, char array has to be determinated, no more than 6 letters and i can't find another way, at least on C++ to make it, thanks a lot.
To assign a C style string (char array) to a std::string, you can use the following code:
std::string foo = c_style_string;
In addition, the variable on the left-hand side of the assignment operator (equal sign) is changed to the value of the variable on the right-hand side. char[50] = string will not compile.
Convert char array to string
char cArray[12] = "hello world";
string str(cArray);
Our instructor told us that a string is the array of characters, and I was wondering whenever we use any array statically, we have to define its size before compiling the pro-gramme in C++ then why don't we do same with the string?
Thanks in advance.
The compiler can choose an array's size automatically to match its initial content, for example:
int a[] = { 3, 5, 2 };
So this is not something that string literals have and other arrays don't.
The string is an object, which is smarter than a character array. A character array is just an allocation in memory, it has no logic associated with it. However the string (because it is an object) is able to manage its own memory and expand as needed.
In C++ you can overload operators. Because the string class has its [ ] operators overloaded you can use the string as an array and access individual characters. However when you use the [ ] operators you are actually invoking a method on the string (namely operator[ ]).
So you can create a string, expand by adding to it, and access individual characters in it:
string str1 = "Hello "; // create a string and assign value
string str2("World"); // use the constructor to assign a value
str1 += str2; // append one string to another
cout << str1[0]; // should print H
But even though the opeartor overloading give it has the same feel as an array, it's actually an object.
if we talk about char* arr = "hello world";
now here "hello world" is given memory through a string object and the object is initialized by the constructor of the String class.
if we say String str = "hello world";
here again constructor of String class is called and it initializes the str object of String to point to the starting address of "hello world" which is stored somewhere in memory.
here we do not have to give the size, instead of that constructor of string class is doing all the trick of allocating dynamic memory and initializing.
I am trying to create an array of pointers to strings. I want each of the strings to have only 3 chars. This is the code I have so far:
string **ptr=new string *[100]; // An array of 100 pointers to strings
for (i=0;i<100; i++) // Assigning each pointer with a new string
{
ptr[i]=new string;
(*ptr[i])[3];
}
I am having trouble with the line (*ptr[i])[3]). If I were to create a srting with only 3 chars not via a pointer I would write:
string str[3];
How do I assign 3 chars with the pointer? Thanks!
std::vector<std::string> vec(100, " ");
That does exactly what you are looking for without the need to manage memory yourself.
string str[3];
That does not create a string with 3 characters, but an array of 3 strings.
(*ptr[i])[3]; simply accesses the fourth character in the string, it doesn't resize it. The std::string DOES provide a resize() method though.
As already mentioned, string str[3] creates an array of three strings but I don't think you're trying to talk about that.
As already pointed out, you can use the string ctor that takes a size argument and a fill char, like so:
ptr[i]=new string( 3, ' ' );
And of course you should use vector.
I know I can convert character arrays to std::string using: string str(array);
But the question is: Could take part of it and convert to string? (for example, first 15 characters)
By the way, my array is defined on the stack.
Thanks.
You use the constructor that takes two iterators (pointers, which arrays decay to, model Random Access Iterators):
std::string str(array, array+15);
This way you can take any part of the array, not just first 15 characters.
In case you have a char array, use the std::string's constructor, which takes 2 iterators:
std::string str(arr, arr + 15);
In case you have an instance of std::string already, use std::string::substr:
std::string str("my long string full of words");
std::cout << "'" << str.substr(0,15) << "'";
outputs: 'my long string '