kristofer ha revisionato questo gist . Vai alla revisione
1 file changed, 59 insertions
splitting-a-string.md(file creato)
| @@ -0,0 +1,59 @@ | |||
| 1 | + | ## Splitting a String | |
| 2 | + | ||
| 3 | + | into a list or array of strings. | |
| 4 | + | ||
| 5 | + | Key differences: | |
| 6 | + | ||
| 7 | + | - Python returns a list directly | |
| 8 | + | - Java returns an array (String[]), which you can convert to List if needed | |
| 9 | + | - Python uses split() with no argument to split by any whitespace | |
| 10 | + | - Java requires explicit delimiter - use split("\\s+") for any whitespace | |
| 11 | + | ||
| 12 | + | in Python | |
| 13 | + | ||
| 14 | + | ||
| 15 | + | ```python | |
| 16 | + | # Basic split (by spaces) | |
| 17 | + | text = "hello world python programming" | |
| 18 | + | words = text.split() | |
| 19 | + | # Result: ['hello', 'world', 'python', 'programming'] | |
| 20 | + | ||
| 21 | + | # Split by specific delimiter | |
| 22 | + | data = "apple,banana,orange,grape" | |
| 23 | + | fruits = data.split(',') | |
| 24 | + | # Result: ['apple', 'banana', 'orange', 'grape'] | |
| 25 | + | ||
| 26 | + | # Split with limit | |
| 27 | + | text = "one-two-three-four" | |
| 28 | + | parts = text.split('-', 2) # Split only twice | |
| 29 | + | # Result: ['one', 'two', 'three-four'] | |
| 30 | + | ``` | |
| 31 | + | ||
| 32 | + | in Java | |
| 33 | + | ||
| 34 | + | ```java | |
| 35 | + | // Basic split (by spaces) | |
| 36 | + | String text = "hello world java programming"; | |
| 37 | + | String[] words = text.split(" "); | |
| 38 | + | // Result: ["hello", "world", "java", "programming"] | |
| 39 | + | ||
| 40 | + | // Split by specific delimiter | |
| 41 | + | String data = "apple,banana,orange,grape"; | |
| 42 | + | String[] fruits = data.split(","); | |
| 43 | + | // Result: ["apple", "banana", "orange", "grape"] | |
| 44 | + | ||
| 45 | + | // Split with limit | |
| 46 | + | String text = "one-two-three-four"; | |
| 47 | + | String[] parts = text.split("-", 3); // Split only 3 times | |
| 48 | + | // Result: ["one", "two", "three-four"] | |
| 49 | + | ||
| 50 | + | // Convert to List if needed | |
| 51 | + | List<String> fruitList = Arrays.asList(fruits); | |
| 52 | + | // Or for a mutable list: | |
| 53 | + | List<String> fruitList = new ArrayList<>(Arrays.asList(fruits)); | |
| 54 | + | ``` | |
| 55 | + | ||
| 56 | + | ||
| 57 | + | ||
| 58 | + | ||
| 59 | + | ||
Più nuovi
Più vecchi