Section 3.3 String
Strings in Java and Python are quite similar. Like Python, Java strings are immutable. However, manipulating strings in Java is not quite as obvious since Strings do not support an indexing or slicing operator. That is not to say that you canβt index into a Java string, you can. You can also pull out a substring just as you can with slicing. The difference is that Java uses method calls where Python uses operators.
In fact, this is the first example of another big difference between Java and Python. Java does not support any operator overloading. Table 3 maps common Python string operations to their Java counterparts. For the examples shown in the table we will use a string variable called βstrβ
| Python | Java | Description |
|---|---|---|
str[3] |
str.charAt(3) |
Return character in 3rd position |
str[2:4] |
str.substring(2,4) |
Return substring from 2nd up to but not including 4th |
len(str) |
str.length() |
Return the length of the string |
str.find('x') |
str.indexOf('x') |
Find the first occurrence of x |
str.split() |
str.split('\s') |
Split the string on whitespace into a list/array of strings |
str.split(',') |
str.split(',') |
Split the string at ',' into a list/array of strings |
str + str |
str + str or str.concat(str)
|
Concatenate two strings together |
str.strip() |
str.trim() |
Remove any whitespace at the beginning or end |
You have attempted of activities on this page.
