Java: Strings

A string is the programming term for text. More properly it can be thought of as a string of characters. We’ve already used strings whenever we’ve used the double quote enclosed text in the println() function. We can also use strings with variables. The string variable in Java is defined with a capitalised String.

Exercise 201: Strings

A simple example program that uses strings and performs common operations on them.

String s1 = "May the force be with you!";
String s2 = "Always two there are";

System.out.println( s1.length() );
System.out.println( s2.length() );

System.out.println( s1.charAt(0) );
System.out.println( s1.charAt(1) );
System.out.println( s1.charAt(1) + 1 );
System.out.println( s1.charAt(2) );

System.out.println( s2.indexOf(" ") );
System.out.println( s2.lastIndexOf(" ") );
System.out.println( s1.substring(8, 12) );
System.out.println( s2.replace("two", "three") );
System.out.println( s1.toUpperCase() );
System.out.println( s2.toLowerCase() );

String s3 = s1 + " " + s2;  // concatenation
System.out.println( s3 );

Exercise 202: User input: Strings

To input from the user some text as a string, it works very similar to numbers except we use the nextLine() function.

java.util.Scanner reader = new java.util.Scanner(System.in);

System.out.print("What is your full name? ");
String fullName = reader.nextLine();
System.out.println("Hello, "+n);
int space = fullName.lastIndexOf(" ");
String givenName = fullName.substring(0, space);
String familyName = fullName.substring(space+1, fullName.length());
System.out.println("Your given name(s) are "+givenName);
System.out.println("Your family name is "+familyName);

Exercises 203 to 206: Strings

Hello
Hello again
String pq = "Eddie Haskel";
int hm = pq.length();
String ed = pq.substring(hm - 4); 
System.out.println(ed);

(exercises 203-206 adapted from codingbat.org; 207-210 adapted from Blue Pelican Java)