String Methods Flashcards
Declaring a String
String str = “Welcome”;
Find Character at nth position of the string
Char Ch = str.charAt(nth);
Convert a String into Char Array
Char[] array = str.toCharArray();
Covert a String to Int
Method 1 : Using Integer.parseInt String str3="1234"; int num3 = Integer.parseInt(str3) ============================== Method 2: Using Integer.valueOf String str="1122"; int num = Integer.valueOf(str);
Convert a int to String
Method 1: Using Integer.toString(int i) int ivar2 = 200; String str2 = Integer.toString(ivar2); ================================= Method 2: Using String.valueOf(int i) int ivar = 111; String str = String.valueOf(ivar);
Convert string to Double
String str3 = 11.22;
Method 1 : Double var = Double.parseDouble(str3);
Method 2 : Double var3 = Double.valueOf(str3);
Convert ASCII to Char
I/P - int num[] = {65, 120, 98, 75, 115};
String str1 =null;
String str2 =null;
for(int i: num){
Method 1 -> str1 = Character.toString((char)i);
Method 1 -> str2 = String.valueof(Character.toChar()int);
System.out.print(str+ “ “);
}
O/P - A x b K s
Convert Char to ASCII
char character = ‘a’;
int ascii = (int) character;
Covert a string to ArrayList
String num = "22,33,44,55,66,77"; String[] str = num.split(","); List arraylist = new ArrayList(); arraylist = Arrays.asList(str)
Find the Length of the string
int Length = str.length();
find the index of first occurrence of the specified character ch in the string
int Position = str.indexOf(Char);
Add One string to other
String Combined = str1.concat(str2)
Splitting the string
Char[] array = str.split(“,or / or any Regex”);
Convert All the characters to Upper Case
String newUpper = str.toUpperCase();
Convert All the characters to Lower case
String newLower = str.toLowerCase();
string matches
Input :
String str = new String(“Java String Methods”);
System.out.print(“Regex: (.)String(.) matches string? “ );
Output: TRUE
Equality Check of two strings
stringOne.equal(stringTwo) returns TRUE if matches else false
Some basic Validation for String Input Questions (Applies to Most)
- Is the string null ? -> (input == null)
- Is the string empty ? -> (input.isEmpty()) or (input.length == 0)
- Does the string have only one char ? -> (input.length == 1)
Whats the difference between string.isEmpty() and string == null?
The empty string is a string with zero length. The null value is not having a string at all.
The expression s == null will return false if s is an empty string.
The second version will throw a NullPointerException if the string is null.
Here’s a table showing the differences:
+——-+———–+———————-+
| s | s == null | s.isEmpty() |
+——-+———–+———————-+
| null | true | NullPointerException |
| “” | false | true |
| “foo” | false | false |
+——-+———–+———————-+