Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between Strings in C++ and Java

Tags:

java

c++

string

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?

like image 812
TheLostMind Avatar asked Sep 19 '13 07:09

TheLostMind


People also ask

What is difference between a string in Java and string in C C++?

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.

What is the difference between strings and C strings?

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.

What is the difference between C and Java?

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


1 Answers

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

like image 149
Jon Skeet Avatar answered Oct 05 '22 14:10

Jon Skeet