C :
String declaration :
char A[1000]; // creates a character array of size 1000.
char *A = (char *) malloc(1000 * sizeof(char)); // creates a character array of size 1000
Accessing ith element :
A[i]
The end of string :
Strings have to end with a '\0' character.
All C input functions like scanf do it automatically.
Direct string assignments like `char A[20] = "Hello";` does it automatically as well.
Length of string :
strlen(A); // O(n) operation where n is length of string
C++
C style char arrays work in C++ as well. However, C++ provides string which is much more powerful than C arrays. We will be using C++ strings in most of the problems on this judge.
String declaration :
string A; // declares an empty string
string A = "Hello"; // declares string initialized to "Hello".
Accessing ith element :
A[i] // O(1)
Size ( number of elements ) of the string :
A.length() // O(1)
Appending to the string :
A += "Hello"; // Appends Hello to the string. O(n) operation
A.push_back('H'); // Append character H to the string. O(1) operation.
JAVA :
Java has strings as well which are very similar to C++ string. However java strings are immutable. As such, if you plan to keep appending to the string, then better use StringBuilder.
Array declaration :
String A = new String(); // declares an empty string. O(1)
String A = new String("Hello"); // declares string initialized to "Hello"
OR for mutable string :
StringBuilder A = new StringBuilder(); // empty string
StringBuilder A = new StringBuilder("Hello"); // stringbuilder initialized to "Hello".
Accessing ith element :
A.charAt(i) // O(1). Works for both String and StringBuilder
Size of the string :
A.length() // O(1) operation
Adding characters to the string :
String : A.concat("Hello"); // O(n) operation. Creates another copy of the string as string is immutable.
StringBuilder : A.append("Hello"); // O(l) operation where l is the length of the string being appended. Much more efficient.
PYTHON
Python has string which is very similar to java string. Its immutable.
String declaration :
A = "" # empty string
A = "Hello" # string initialized to "Hello"
Accessing the ith element :
A[i] # O(1)
Adding chars to the string :
A = A + "Hello" # O(n) operation and a new copy is created
An alternative way if you are going to do a lot of appends :
l = []
l.append('string1')
l.append('string2')
l.append('string3')
A = ''.join(l)