A String is a collection of characters stored together to represent text in a program.
These characters can be letters, numbers, symbols, or spaces.
String is immutable
Example:
"Priya"
"Hello World"
"12345"
"Java@2026"
All of these are strings because they store text inside quotes.
Accessing the First Character of a String
Python
name = "priya"
print(name[0])
In JavaScript
const name = "priya"
console.log(name[0])
Accessing the middle Character of a String
Python
name = "priya"
# Find the middle index
middle_index = len(name) // 2
# Print the middle character
print(name[middle_index])
JavaScript
const name = "priya";
// Find the middle index
const middleIndex = Math.floor(name.length / 2);
// Print the middle character
console.log(name[middleIndex]);
Accessing the last Character of a String
Python
name = "priya"
print(name[-1])
JavaScript
const name = "priya";
// Get the last character
console.log(name[name.length - 1]); // Output: "a"
capitalize the first letter of a string
In Python
name = "priya"
# Capitalize only the first letter
result = name[0].upper() + name[1:]
print(result)
In JavaScript
let name = "priya";
// Capitalize only the first letter
let result = name[0].toUpperCase() + name.slice(1);
console.log(result);
Java
Changing Case of Specific Characters in a String
In Python
name = "priya"
length = len(name)
result = (
name[0].upper() + # First character uppercase
name[1:length // 2] + # Characters from 1 to middle-1 unchanged
name[length // 2].upper() + # Middle character uppercase
name[length // 2 + 1:length - 1] + # Characters after middle to second last unchanged
name[length - 1].upper() # Last character uppercase
)
print(result)
In JavaScript
let name = "priya";
let len = name.length;
let result =
name[0].toUpperCase() +
name.substring(1, Math.floor(len / 2)) +
name[Math.floor(len / 2)].toUpperCase() +
name.substring(Math.floor(len / 2) + 1, len - 1) +
name[len - 1].toUpperCase();
console.log(result);
Java
public class ChangeCase {
public static void main(String[] args) {
String name = "priya";
int len = name.length();
int mid = len / 2;
// Build the new string
String result =
name.substring(0, 1).toUpperCase() + // First character uppercase
name.substring(1, mid) + // Characters from 1 to middle-1 unchanged
name.substring(mid, mid + 1).toUpperCase() + // Middle character uppercase
name.substring(mid + 1, len - 1) + // Characters after middle to second last unchanged
name.substring(len - 1).toUpperCase(); // Last character uppercase
System.out.println(result);
}
}
Top comments (0)