Ultima attività 1763751699

Revisione 181c9b952b0d9b5d0abae3cfd975a1e7cf3ad52a

string-work.md Raw

Working with Strings

In both python and Java, samples of working with common string operations: split, capitalization, concatenation, replacing characters, working with sentences.

Key differences:

  • Python: Has built-in title(), capitalize() methods; f-strings for formatting
  • Java: More verbose; often requires manual implementation or StringBuilder
  • Python: Strings are immutable but syntax is cleaner
  • Java: Strings are also immutable; use StringBuilder for efficiency with multiple operations

in Python

# Split operations
text = "hello world python"
words = text.split()                    # ['hello', 'world', 'python']
csv = "apple,banana,orange"
fruits = csv.split(',')                 # ['apple', 'banana', 'orange']

# Capitalization
name = "john doe"
print(name.capitalize())                # "John doe"
print(name.title())                     # "John Doe"
print(name.upper())                     # "JOHN DOE"
print(name.lower())                     # "john doe"

# Concatenation
# Method 1: + operator
greeting = "Hello" + " " + "World"      # "Hello World"

# Method 2: join() - more efficient for multiple strings
words = ["Python", "is", "awesome"]
sentence = " ".join(words)              # "Python is awesome"

# Method 3: f-strings (Python 3.6+)
name = "Alice"
age = 25
message = f"{name} is {age} years old"  # "Alice is 25 years old"

# Replacing characters/substrings
text = "Hello World"
new_text = text.replace("World", "Python")  # "Hello Python"
phone = "123-456-7890"
clean = phone.replace("-", "")              # "1234567890"

# Working with sentences
sentence = "this is a sentence. and another one."
# Capitalize first letter of each sentence
sentences = sentence.split('. ')
capitalized = '. '.join(s.capitalize() for s in sentences)
# Result: "This is a sentence. And another one."

# Strip whitespace
messy = "  hello world  \n"
clean = messy.strip()                   # "hello world"

# Check string properties
text = "Hello123"
print(text.isalnum())                   # True
print(text.isalpha())                   # False
print(text.startswith("Hello"))         # True
print(text.endswith("123"))             # True

in Java

// Split operations
String text = "hello world java";
String[] words = text.split(" ");           // ["hello", "world", "java"]
String csv = "apple,banana,orange";
String[] fruits = csv.split(",");           // ["apple", "banana", "orange"]

// Capitalization
String name = "john doe";
// Capitalize first letter only
String capitalized = name.substring(0, 1).toUpperCase() + name.substring(1);
// Result: "John doe"

// Title case (manual - Java doesn't have built-in)
String[] words = name.split(" ");
StringBuilder titleCase = new StringBuilder();
for (String word : words) {
    titleCase.append(word.substring(0, 1).toUpperCase())
             .append(word.substring(1).toLowerCase())
             .append(" ");
}
String title = titleCase.toString().trim(); // "John Doe"

// Upper and lower case
String upper = name.toUpperCase();          // "JOHN DOE"
String lower = name.toLowerCase();          // "john doe"

// Concatenation
// Method 1: + operator (creates new strings)
String greeting = "Hello" + " " + "World";  // "Hello World"

// Method 2: StringBuilder (efficient for multiple operations)
StringBuilder sb = new StringBuilder();
sb.append("Java").append(" is ").append("awesome");
String sentence = sb.toString();            // "Java is awesome"

// Method 3: String.join()
String[] words = {"Java", "is", "awesome"};
String joined = String.join(" ", words);    // "Java is awesome"

// Method 4: String.format()
String name = "Alice";
int age = 25;
String message = String.format("%s is %d years old", name, age);
// Result: "Alice is 25 years old"

// Replacing characters/substrings
String text = "Hello World";
String newText = text.replace("World", "Java");     // "Hello Java"
String phone = "123-456-7890";
String clean = phone.replace("-", "");               // "1234567890"

// Replace first occurrence only
String repeated = "abc abc abc";
String replaced = repeated.replaceFirst("abc", "xyz"); // "xyz abc abc"

// Working with sentences
String sentence = "this is a sentence. and another one.";
// Capitalize sentences (manual approach)
String[] sentences = sentence.split("\\. ");
StringBuilder result = new StringBuilder();
for (String s : sentences) {
    if (!s.isEmpty()) {
        result.append(Character.toUpperCase(s.charAt(0)))
              .append(s.substring(1))
              .append(". ");
    }
}
String capitalized = result.toString().trim();
// Result: "This is a sentence. And another one."

// Trim whitespace
String messy = "  hello world  \n";
String clean = messy.trim();                // "hello world"

// Check string properties
String text = "Hello123";
System.out.println(text.matches("[a-zA-Z0-9]+")); // true (alphanumeric)
System.out.println(text.matches("[a-zA-Z]+"));    // false (not just letters)
System.out.println(text.startsWith("Hello"));     // true
System.out.println(text.endsWith("123"));         // true