Java String

Kevin FOO
1 min readApr 28, 2022

--

My cheat sheet of string related functions. I’ll add more along the way when I use more of it.

Comparison

String one   = "hello";
String two = "world";
String three = "hello";
String four = new String("hello");
String five = "HELLO"
System.out.println(one==two); # false
System.out.println(one==three); # true
System.out.println(one==four); # false
# best to use this
System.out.println(one.equals(two)); # false
System.out.println(one.equals(three)); # true
System.out.println(one.equals(four)); # true
System.out.println(one.equalsIgnoreCase(five)); # true

String To Char Array

# string to char array
String hw = "hello world";
char[] ca = hw.toCharArray();
# print the array
for(char c:ch){
System.out.println(c);
}

Char To ASCII Number

# convert char to ASCII number
System.out.println((int)'A');

Char To String

# char to string
char c = 'A';
String s = String.valueOf(c);
System.out.println(s);

To Lower/Upper Case

String hw = "Hello World";

# to lower case
System.out.println(hw.toLowerCase());
# to upper case
System.out.println(hw.toUpperCase());

Substring

# substring params are start index, end index
String hw = "hello world";
System.out.println(hw.substring(6,7)); # w

Reverse

String s = "hello world";
char[] ca = s.toCharArray();
ArrayList<String> al = new ArrayList<String>();
for(char c:ca){
al.add(String.valueOf(c));
}
Collections.reverse(al);
System.out.println(String.join("",al));

Split

String s = "the!quick@brown#fox$jumps%over^the&lazy dog";
String[] a = s.split("[!@#$%^& ]");
for(String z:a){
System.out.println(z);
}

String To Integer

String s = "88";
int i = Integer.parseInt(s);
System.out.println(i);

< Back to all the stories I had written

--

--

Kevin FOO
Kevin FOO

Written by Kevin FOO

A software engineer, a rock climbing, inline skating enthusiast, a husband, a father.

No responses yet