You are on page 1of 18

Java Programming 1

Lecture 6
Strings and Characters
Fundamentals of Characters and Strings

• A character:
• Single lower case letter : a – z
• Single upper case letter : A – Z
• Digits : 0 - 9
• Special characters : +, -, *, /, $, ? and so on

• A string is a combination of 2 or more of such characters.


• “Tracy A. Chapman”
• “99, Jalan 22/4b, Semenyih”

• To declare a character:
char a = ‘x’;

• To declare a string:
String b = “This is a string”;
Declaring character and some character class function
public class string1
{
public static void main (String[] args)
{
char a = 'f';
char b = '3';
int c = 3;
char d = ' ';
char e = 'G';

System.out.println ("Is " + a + " a character: " + Character.isLetter(a));


System.out.println ("Is " + b + " a letter: " + Character.isLetter(b));
System.out.println ("Is " + a + " a digit: " + Character.isDigit(a));
System.out.println ("Is \'" + b + "\' a digit: " + Character.isDigit(b));
System.out.println ("Is " + c + " a digit: " + Character.isDigit(c) + " ***");
System.out.println ("Is " + a + " uppercase: " + Character.isUpperCase(a));
System.out.println ("Is " + a + " lowercase: " + Character.isLowerCase(a));
System.out.println ("Is " + a + " a space: " + Character.isWhitespace(a));
System.out.println ("Is " + d + " a space: " + Character.isWhitespace(d));
System.out.println ("Change " + a + " to uppercase: " + Character.toUpperCase(a));
System.out.println ("Change " + e + " to lowercase: " + Character.toLowerCase(e));
}
Character class function

Function Description Result


isLetter Checks if the character is a letter True/False
isDigit Checks if the character is a digit True/False
**Note that int is not a character
isUpperCase Checks if the character is uppercase True/False
isLowerCase Checks if the character is lowercase True/False
isWhitespace Checks if the character is a spacing (white space) True/False
toUpperCase Changes the character to an uppercase Resultant output
toLowerCase Changes the character to lower case Resultant output
String as an array of characters

• When we declare a String, we’re in some ways declaring an array


of characters (because string = collection of characters)
• “Hello World”
(0) (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)
H e l l o W o r l d
Declaring string and some string class function
public class string2
{
public static void main (String[] args)
{
String a = "hello world";
String b = a + " everyone";
String c = "";
char charArray[] = new char[5];

b = "The length of \"" + b + "\" is " + b.length(); //string.length() is the total length of the string
System.out.println(b);

for (int x=a.length()-1;x>=0;x--)


{
c = c + a.charAt(x); //string.charAt() take from the string, a character at index x
}
System.out.println ("\n" + c + "\n");

a.getChars(6,11,charArray,0); //string.getChars() collects a set of characters from string and insert into a char array.
for (int x=0;x<charArray.length;x++)
{
System.out.print(charArray[x]);
}
}
Functions from previous example

• “Hello World”
stringname.length()
Size of the array
which is 11

(0) (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)
H e l l o W o r l d

stringname.getChar(6,11,charArray,0)
stringname.charAt(1) This function will get characters from
Character at index 1 6th index to (11 minus 1) index.
of string = ‘e’ It will then store it in a character array
called charArray starting from index 0
Comparing strings
Refer to comparingstring.java
• There is a difference when you create:
1. String a = new string (“hello”);
2. String a = “hello”;

3. Creates a new object that is a copy of “hello”


4. Create a string that is “hello”

• stringname.equals (“text”);
• This function compares if the “text” is equal to the data in stringname.
• Can be used to copy “text” in an object or variable.

• stringname == “text”
• This is used to check if stringname IS “text”
• Will return false if stringname is an object (because the object is just a copy not actually “text”)
Comparing strings
• stringname.equalsIgnoreCase (“text”);
• Compares the stringname with “text” ignoring case

• stringname.regionMatches (param1, param2, param3, param4, param5)


• Used to check if the region of one string matches the region of another string.
 param1 : (optional) TRUE if we want to ignore case
 param2 : starting index of original string
 param3 : name of second string
 param4 : starting index of second string
 param5 : length of the compared region
String checking functions

Refer to checkstring.java
• stringname.startsWith (“text”)
• This function compares if the data in stringname has starting characters that
matches “text”

• stringname.startsWith (“text”,indexnum)
• This function compares if the data in stringname has starting characters that
matches “text” beginning from indexnum.

• stringname.endsWith (“text”)
• This function compares if the data in stringname has ending characters that
matches “text”
String searching functions

Refer to searchstring.java
• stringname.indexOf (“text”, startingindex)
• This function returns the first index of “text” and the search starts from
startingindex.
• Startingindex parameter is optional

• stringname.lastIndexOf (“text”, endingindex)


• This function returns the first index of “text” and the search will end at
endingindex
• Endingindex parameter is optional
String extraction functions

Refer to extractstring.java
• stringname.substring (startingindex, endingindex)
• This function will return a substring starting from the startingindex up to the
value before the endingindex
String concatenation functions

public class concatstring


{
public static void main (String[] args)
{
String a = "Good students ";
String b = "are not afraid of Java Programming";

System.out.println (a.concat(b));
System.out.println (a);
}
}

stringname.concat(stringnameb)
• This function will concatenate stringname to stringnameb
• Note that stringname or stringnameb does not change value at all.
String trim function

public class trimstring


{
public static void main (String[] args)
{
String a = “ this string is weird ";

System.out.println (a.trim());
}
}

• To remove leading and trailing spaces on a string, use:


stringname.trim()
• Note that the rest of the string remains unchanged, including spaces in between characters.
String replace all function
public class replacestring
{
public static void main (String[] args)
{
String a = “ this string is weird ";

a = a.replaceAll(“\\s”, “”);
System.out.print (a);
}
}

stringname.replaceAll(“regex”, “newchar”)
• This function will replace all regex values found in stringname with “newchar”
• Important regex:
i. .  all characters
ii. \d  all digits ; \D  all non digits
iii. \s  all whitespaces ; \S  all non whitespaces
iv. \w  all word characters; \W  all non word characters
To use scanner method to input string

• So far all user input has been using JOptionPane.showInputDialog


• However if you wish to use the command prompt to ask for user
input, use the following code:
import java.util.Scanner;
Scanner sc = new Scanner (System.in);
stringname = sc.nextLine();
• This “scanner” will read the entire user input until a nextline
command (ie Enter) is entered.
Java string practice

1. Write a program for the user to input a string. Check if the string is
palindrome.
• Palindrome example: reviver

2. Write a program for the user to input a string. Check if the string is
an anagram.
• Anagram example: roots is an anagram of torso.

3. Write a program for the user to input a string. Use bubble sort,
selection sort and insertion sort to sort out the characters in the
string.
Java string practice 2

4. Write a program that accepts the following data from a user


using Command Prompt and input into an array. Before any data
is accepted, it MUST fulfil the condition in the brackets, otherwise
ask the user to enter again that particular information with an error
message:
• Name (Must be all characters, minimum 2 words)
• Address (Must have all essentials, up to your creativity to check)
• Phone (must be all digits with one “-”for area code, ie 000-00000000)
• IC or Passport number (if IC – all digits with 2 “-”in between ie
000000-00-0000, if passport one character and 8 numbers ie
A00000000)
• Email (must be in aaaa@bbbb.ccc format)

You might also like