String
A string is actually an array of
unicode characters
.
String Comparison
String has its own compare function
Can we use "==" to compare two strings?
Depends on
Does the language support
operator overloading
?
Yes (like C++), we may use "==" to compare strings
No (like Java), we may not use "==" to compare two strings. "==" actually compares whether these two objects are the same object.
For Java, use
or
Immutable or Mutable
In some languages (like C++), string is mutable
, while in Java, string is immutable
Time Complexity of Built-in Operations
For instance, if the length of the string isN
, the time complexity of both finding operation and substring operation isO(N)
.
Beware of String Concatenation in Java
In Java, since the string is
immutable
, concatenation works by first allocating enough space for the new string, copy the contents from the old string and append to the new string.
In Java, using "+" for string concatenation, the time complexity will be O(n)
For the following, total time complexity in total will be O(n^2)
Mutate String in Java
1. convert it to a char array
2. use some other data structures like StringBuilder
StringBuilder
The below code runs in O(n) time complexity.
Last updated