Dernière activité 1763750838

split a string in both Python and Java

Révision 32757daff8a263c3c20d45d6d01d32d9e92b7dbd

splitting-a-string.md Brut

Splitting a String

into a list or array of strings.

Key differences:

  • Python returns a list directly
  • Java returns an array (String[]), which you can convert to List if needed
  • Python uses split() with no argument to split by any whitespace
  • Java requires explicit delimiter - use split("\s+") for any whitespace

in Python

# Basic split (by spaces)
text = "hello world python programming"
words = text.split()
# Result: ['hello', 'world', 'python', 'programming']

# Split by specific delimiter
data = "apple,banana,orange,grape"
fruits = data.split(',')
# Result: ['apple', 'banana', 'orange', 'grape']

# Split with limit
text = "one-two-three-four"
parts = text.split('-', 2)  # Split only twice
# Result: ['one', 'two', 'three-four']

in Java

// Basic split (by spaces)
String text = "hello world java programming";
String[] words = text.split(" ");
// Result: ["hello", "world", "java", "programming"]

// Split by specific delimiter
String data = "apple,banana,orange,grape";
String[] fruits = data.split(",");
// Result: ["apple", "banana", "orange", "grape"]

// Split with limit
String text = "one-two-three-four";
String[] parts = text.split("-", 3);  // Split only 3 times
// Result: ["one", "two", "three-four"]

// Convert to List if needed
List<String> fruitList = Arrays.asList(fruits);
// Or for a mutable list:
List<String> fruitList = new ArrayList<>(Arrays.asList(fruits));