Sure! Let's compare string in different programming languages. I'll explain how strings are handled in Python, Java, C++, and JavaScript. These are the most common languages that use strings.
✅ 1. Python (Python 3)
String Basics
- Strings are immutable.
- Strings are enclosed in single quotes (
'), double quotes ("), or triple quotes (''').
Example:
s = 'Hello'
print(s) # Output: Hello
s = "Hello World"
print(s) # Output: Hello World
s = '''Hello
World'''
print(s) # Output: Hello
World
String Methods
len(s): Get the length of the string.s.upper(): Convert to uppercase.s.lower(): Convert to lowercase.s.strip(): Remove leading/trailing whitespace.s.split(): Split into a list (by whitespace).s.find('x'): Find the index of a character.
✅ 2. Java
String Basics
- Strings are immutable.
- Strings are declared using the
Stringclass.
Example:
String s = "Hello";
System.out.println(s); // Output: Hello
s = "Hello World";
System.out.println(s); // Output: Hello World
String Methods
s.length(): Get the length of the string.s.toUpperCase(): Convert to uppercase.s.toLowerCase(): Convert to lowercase.s.trim(): Remove leading/trailing whitespace.s.split(" "): Split into a list (by space).s.indexOf("x"): Find the index of a character.
✅ 3. C++
String Basics
- Strings are immutable.
- Strings are declared using the
std::stringclass.
Example:
#include <iostream>
#include <string>
int main() {
std::string s = "Hello";
std::cout << s << std::endl; // Output: Hello
s = "Hello World";
std::cout << s << std::endl; // Output: Hello World
return 0;
}
String Methods
s.length(): Get the length of the string.s.toUpperCase(): Convert to uppercase (C++ doesn't have a built-in method for this, but you can usestd::transformorstd::string::c_str()).s.substr(0, 5): Get a substring.s.find("x"): Find the index of a character.
✅ 4. JavaScript
String Basics
- Strings are immutable.
- Strings are declared using the
Stringconstructor or using single quotes.
Example:
let s = "Hello";
console.log(s); // Output: Hello
s = "Hello World";
console.log(s); // Output: Hello World
String Methods
s.length(): Get the length of the string.s.toUpperCase(): Convert to uppercase.s.toLowerCase(): Convert to lowercase.s.trim(): Remove leading/trailing whitespace.s.split(" "): Split into an array.s.indexOf("x"): Find the index of a character.