In C++
I can do something like this...
String s = "abc";
char c = s[i]; // works fine...
But in Java
, if I try doing the same, it throws an error. Why?.
In java
, to achieve the above, I have to do :
s.toCharArray();
How is the implementation of Strings in C++
different from that in Java?
in c++ strings are already treated as array of characters, but in java String is a built in class. it is different from array of characters. In C++, std::string is not an array of characters. E.g. it has a size() member, which char[] lacks.
std::string is compatible with STL algorithms and other containers. C strings are not char * or const char * ; they are just null-terminated character arrays. Even string literals are just character arrays.
C is a compiled language that is it converts the code into machine language so that it could be understood by the machine or system. Java is an Interpreted language that is in Java, the code is first transformed into bytecode and that bytecode is then executed by the JVM (Java Virtual Machine).
In java, to achieve the above, I have to do : s.toCharArray();
Not really. You can use charAt
instead:
char c = s.charAt(i);
Basically, C++ allows user-defined operators - Java doesn't. So the String
class doesn't expose any sort of "indexing" operator; that only exists for arrays, and a String
isn't an array. (It's usually implemented using an array, but that's a different matter.)
EDIT: As noted in comments, the +
operator is special-cased for strings - right in the language specification. The same could have been done for []
, but it isn't - and as it's not in the language specification, and Java doesn't support overloaded operators, it can't be performed in library code. (For example, you can't give custom behaviour to +
for any other class.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With