splitting-a-string.md
· 1.4 KiB · Markdown
原始文件
## 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
```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
```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));
```
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));