Difference between revisions of "String Methods"

From CompSciWiki
Jump to: navigation, search
(Moved the String methods text under equals and changed it a bit, was only talking about equals method. Moved one sentence to intro)
 
(14 intermediate revisions by 4 users not shown)
Line 1: Line 1:
{{Template:1010Topic
+
{{1010Topic
 
|Chapter_TOC=[[Calling Methods]]
 
|Chapter_TOC=[[Calling Methods]]
 
|Previous=[[Calling Methods]]
 
|Previous=[[Calling Methods]]
Line 6: Line 6:
  
 
==Introduction==
 
==Introduction==
You will learn how to use simple API String Methods such as comparing Strings and finding the length of a String. String is just another toolbox and its methods are the tools to simplify work related to Strings.
+
You will learn how to use simple String Methods such as comparing Strings and finding the length of a String. String is just another toolbox and its methods are the tools to simplify work related to Strings.
  
 
==String Methods==
 
==String Methods==
Line 12: Line 12:
  
  
===equals===
+
===<code>equals</code>===
  
  
 
In the beginning of the Java programming learning process, you have learned that the equal sign "==" determines equality of [[Common Primitive Variables|primitive types]] (eg. int, double, char). However, the equals() method is needed to find the equality of two Strings. This method compares two Strings and returns a boolean result <font color="red">(true or false)</font>. True, if they are the same string and false, if they differ in any way. Think of it as a method that is applied to a String to see if it equals another. This method is required for Strings because the ''''='''' symbol is used for assignment purposes. Example:
 
In the beginning of the Java programming learning process, you have learned that the equal sign "==" determines equality of [[Common Primitive Variables|primitive types]] (eg. int, double, char). However, the equals() method is needed to find the equality of two Strings. This method compares two Strings and returns a boolean result <font color="red">(true or false)</font>. True, if they are the same string and false, if they differ in any way. Think of it as a method that is applied to a String to see if it equals another. This method is required for Strings because the ''''='''' symbol is used for assignment purposes. Example:
 +
  
 
====Code====
 
====Code====
Line 41: Line 42:
 
}}
 
}}
  
{{OutputBlock
+
Ouptut
|Code=C:\Users\umchan99\assignment files\programs a6>javac testStrings.java
+
  
C:\Users\umchan99\assignment files\programs a6>java testStrings
+
{{OutputBlock
 +
|Code=
 
String equals I am test
 
String equals I am test
 
}}
 
}}
 +
 +
  
 
The above example will result in the if statement being true. Note that equals() must be applied to a string variable.
 
The above example will result in the if statement being true. Note that equals() must be applied to a string variable.
  
===equalsIgnoreCase===
 
This method is the same as the one above but the result will be true even if the cases are different. "I AM TEST" would be the same as "i am test".
 
  
===indexOf===
+
===<code>equalsIgnoreCase</code>===
This method finds the location of a specific character or String inside a given String. For example:
+
This method is the same as the <code>equals</code> method but the result will be true even if the cases are different. "I AM TEST" would be the same as "i am test".
 +
 
 +
 
 +
===<code>indexOf</code>===
 +
This method finds the location of a specific character or String inside a given String. In the following example, <code>indexOf</code> is used first to find the location of the <code>String</code> " ", and then the character ' '. <em>Note the different use of the " " and the ' ' to represent the <code>String</code> space and the <code>char</code> space.  Both are valid.</em>
 +
 
 +
 
 
====Code====
 
====Code====
 
{{CodeBlock
 
{{CodeBlock
Line 62: Line 69:
 
public static void main(String args[])
 
public static void main(String args[])
 
{
 
{
final String NAME = "Henry VIII" ;
+
        String NAME = "Henry VIII" ;
 +
 
 +
                // Use String method indexOf to find the location of the String " "
 
System.out.println("The first name is " + NAME.indexOf(" ") + " characters long") ;
 
System.out.println("The first name is " + NAME.indexOf(" ") + " characters long") ;
//above line makes use of a string argument in indexOf
+
 
 +
                // Use String method indexOf to find the locate of the Char ' '
 
System.out.println("The first name is " + NAME.indexOf(' ') + " characters long") ;
 
System.out.println("The first name is " + NAME.indexOf(' ') + " characters long") ;
//above line makes use of a character argument in indexOf
 
 
}
 
}
 
}
 
}
 
}}
 
}}
 +
 +
Output
 +
 
{{OutputBlock
 
{{OutputBlock
 
|Code=
 
|Code=
C:\Users\umchan99\assignment files\programs a6>java indexOf
 
 
The first name is 5 characters long
 
The first name is 5 characters long
 
The first name is 5 characters long
 
The first name is 5 characters long
 
}}
 
}}
 +
  
 
The value returned from indexOf is the number of characters to the left of the first occurrence of the argument. The argument can be either a String or a character (both are shown above). If the argument does not appear in the String at all, indexOf returns a value of -1. This method is often used with substring (see below) to extract part of a String.
 
The value returned from indexOf is the number of characters to the left of the first occurrence of the argument. The argument can be either a String or a character (both are shown above). If the argument does not appear in the String at all, indexOf returns a value of -1. This method is often used with substring (see below) to extract part of a String.
  
===length===
+
===<code>length</code>===
 
This method simply returns the number of characters (including spaces, tabs, etc.) in the String that calls it. For example:
 
This method simply returns the number of characters (including spaces, tabs, etc.) in the String that calls it. For example:
 +
 
====Code====
 
====Code====
 
{{CodeBlock
 
{{CodeBlock
Line 95: Line 108:
 
}}
 
}}
  
Which gives the result:
+
Output
 +
 
 
{{OutputBlock
 
{{OutputBlock
 
|Code=
 
|Code=
C:\Users\umchan99\assignment files\programs a6>java Length
 
 
The string's length is: 9
 
The string's length is: 9
 
}}
 
}}
  
===substring===
+
 
 +
===<code>substring</code>===
 
This method is used to extract part of the given String. For example, to separate an incoming name into first and last names, you could use the following code:
 
This method is used to extract part of the given String. For example, to separate an incoming name into first and last names, you could use the following code:
 +
 
====Code====
 
====Code====
 
{{CodeBlock
 
{{CodeBlock
Line 114: Line 129:
 
//Input the name using a GUI dialog with the help of JOptionPane
 
//Input the name using a GUI dialog with the help of JOptionPane
 
final String NAME = JOptionPane.showInputDialog("Enter your name") ;
 
final String NAME = JOptionPane.showInputDialog("Enter your name") ;
 +
 
//Find the location of a space in the string that has been input
 
//Find the location of a space in the string that has been input
 
//so that you can divide the name into first and last name
 
//so that you can divide the name into first and last name
 
final int BLANK_LOC = NAME.indexOf(' ') ;
 
final int BLANK_LOC = NAME.indexOf(' ') ;
 +
 
//get the firstname by selecting the first part of the string
 
//get the firstname by selecting the first part of the string
 
//i.e. till the space appears. The substring parameters allow you to
 
//i.e. till the space appears. The substring parameters allow you to
 
//choose the starting location and the ending location of the substring
 
//choose the starting location and the ending location of the substring
 
final String FIRST_NAME = NAME.substring(0,BLANK_LOC) ;
 
final String FIRST_NAME = NAME.substring(0,BLANK_LOC) ;
 +
 
//similar to the firstname, select the lastname by selecting the part
 
//similar to the firstname, select the lastname by selecting the part
 
//from space till end of string. Here in the substring parameters we are only
 
//from space till end of string. Here in the substring parameters we are only
Line 126: Line 144:
 
//the end of the string.
 
//the end of the string.
 
final String LAST_NAME = NAME.substring(BLANK_LOC+1) ;
 
final String LAST_NAME = NAME.substring(BLANK_LOC+1) ;
 +
 
System.out.println("The First name is "+FIRST_NAME + "\nThe Last name is " + LAST_NAME);
 
System.out.println("The First name is "+FIRST_NAME + "\nThe Last name is " + LAST_NAME);
 
}
 
}
Line 131: Line 150:
 
}}
 
}}
  
This method can have one or two integer arguments. If it has one argument, say 5, substring discards 5 characters from the front of the String and returns what's left.  If it has two arguments, 3 and 5, it discards 3 characters from the front, and then returns what's left up to position 5. The number of characters returned is the difference between the two arguments. For example,
+
This method can have one or two integer arguments. If it has one argument, say 5, substring discards 5 characters from the front of the String and returns what's left.  If it has two arguments, 3 and 5, it discards 3 characters from the front, and then returns what's left up to position 5. The number of characters returned is the difference between the two arguments.  
 +
 
 +
Output
 +
 
 +
If the code is run and the user enters <tt>Charu Chandra</tt> in the <tt>JOptionPane</tt> window, then the following output would be produced.
 +
 
 
{{OutputBlock
 
{{OutputBlock
 
|Code=
 
|Code=
C:\Users\umchan99\assignment files\programs a6>java SubString
 
 
The First name is Charu
 
The First name is Charu
 
The Last name is Chandra
 
The Last name is Chandra
 
}}
 
}}
 +
 
===More Methods===
 
===More Methods===
For a full list of all the String methods you can visit [http://java.sun.com/javase/6/docs/api/java/lang/String.html The API String Methods] and scroll down to the Method Summary table.
+
For a full list of all the String methods you can visit [http://docs.oracle.com/javase/6/docs/api/java/lang/String.html The String API] and scroll down to the Method Summary table.
 +
 
 +
==Summary==
 +
In this section, you have learnt how to make use of various string methods to make operations with strings easier. Particularly, we learnt to use the string methods <code>equals, length, substring and indexOf</code>.  
 
}}
 
}}

Latest revision as of 15:39, 28 March 2012

COMP 1010 Home > Calling Methods


Introduction

You will learn how to use simple String Methods such as comparing Strings and finding the length of a String. String is just another toolbox and its methods are the tools to simplify work related to Strings.

String Methods

equals

In the beginning of the Java programming learning process, you have learned that the equal sign "==" determines equality of primitive types (eg. int, double, char). However, the equals() method is needed to find the equality of two Strings. This method compares two Strings and returns a boolean result (true or false). True, if they are the same string and false, if they differ in any way. Think of it as a method that is applied to a String to see if it equals another. This method is required for Strings because the '=' symbol is used for assignment purposes. Example:


Code

 public class testStrings
{
	public static void main(String args[])
	{
		String testString;
		testString = "I am test";

		if( testString.equals("I am test") ) 
                //if the value of testString equals "I am test", then print the following code
		{
		     System.out.println("String equals I am test");
		}
		else                                 
		//if not print the following
                {
			System.out.println("String equals I am test");	
		}
	}
} 

Ouptut

 String equals I am test 


The above example will result in the if statement being true. Note that equals() must be applied to a string variable.


equalsIgnoreCase

This method is the same as the equals method but the result will be true even if the cases are different. "I AM TEST" would be the same as "i am test".


indexOf

This method finds the location of a specific character or String inside a given String. In the following example, indexOf is used first to find the location of the String " ", and then the character ' '. Note the different use of the " " and the ' ' to represent the String space and the char space. Both are valid.


Code

 public class indexOf
{
	public static void main(String args[])
	{
	         String NAME = "Henry VIII" ;

                // Use String method indexOf to find the location of the String " "
		System.out.println("The first name is " + NAME.indexOf(" ") + " characters long") ;

                // Use String method indexOf to find the locate of the Char ' '
		System.out.println("The first name is " + NAME.indexOf(' ') + " characters long") ;
	}
} 

Output

 The first name is 5 characters long
The first name is 5 characters long 


The value returned from indexOf is the number of characters to the left of the first occurrence of the argument. The argument can be either a String or a character (both are shown above). If the argument does not appear in the String at all, indexOf returns a value of -1. This method is often used with substring (see below) to extract part of a String.

length

This method simply returns the number of characters (including spaces, tabs, etc.) in the String that calls it. For example:

Code

 public class Length
{
	public static void main(String args[])
	{
		String test = "I am test";
		int length = test.length();			
		System.out.println("The string's length is: " + length);
	}
} 

Output

 The string's length is: 9 


substring

This method is used to extract part of the given String. For example, to separate an incoming name into first and last names, you could use the following code:

Code

 import javax.swing.JOptionPane;
public class SubString
{
	public static void main(String args[])
	{
		//Input the name using a GUI dialog with the help of JOptionPane
		final String NAME = JOptionPane.showInputDialog("Enter your name") ;

		//Find the location of a space in the string that has been input
		//so that you can divide the name into first and last name
		final int BLANK_LOC = NAME.indexOf(' ') ;

		//get the firstname by selecting the first part of the string
		//i.e. till the space appears. The substring parameters allow you to
		//choose the starting location and the ending location of the substring
		final String FIRST_NAME = NAME.substring(0,BLANK_LOC) ;

		//similar to the firstname, select the lastname by selecting the part
		//from space till end of string. Here in the substring parameters we are only
		//providing the begining part of the string. it automatically goes till
		//the end of the string.
		final String LAST_NAME = NAME.substring(BLANK_LOC+1) ;

		System.out.println("The First name is "+FIRST_NAME + "\nThe Last name is " + LAST_NAME);
	}
} 

This method can have one or two integer arguments. If it has one argument, say 5, substring discards 5 characters from the front of the String and returns what's left. If it has two arguments, 3 and 5, it discards 3 characters from the front, and then returns what's left up to position 5. The number of characters returned is the difference between the two arguments.

Output

If the code is run and the user enters Charu Chandra in the JOptionPane window, then the following output would be produced.

 The First name is Charu
The Last name is Chandra 

More Methods

For a full list of all the String methods you can visit The String API and scroll down to the Method Summary table.

Summary

In this section, you have learnt how to make use of various string methods to make operations with strings easier. Particularly, we learnt to use the string methods equals, length, substring and indexOf.

Previous Page: Calling Methods Next Page: Math Methods