Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
CSC1401
Strings (text)
Learning Goals
Working with Strings as a data type (a
class)
Input and output of Strings
String operations
Strings
Anything within double quotes
Examples:
System.out.println(“Hi”);
System.out.println(“The amount is “ +
money);
String name = “Steve”;
Strings as a Java class
Note that we do not need an import
statement
Formally, we should write:
String name;
name = new String (“Steve”);
But it’s ok to write:
String name;
name = “Steve”;
Input of Strings in Java (with
Scanner)
import java.util.*; // needed for scanner
class IOTesting
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
String course;
course = scan.nextLine();
…
Problem Solving with Strings
We typically wish to
Parse strings
Change strings
Java has lots of built-in String methods
(check the Javadocs)
We’ll just look at a few of them
Entering your name
import java.util.*; // needed for scanner
class IOTesting
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
String name;
name = scan.nextLine();
// if the person types in Steve Cooper
// how can we get the first
// and last names???
…
What do we need to be able to do?
Finding a string within a string (in this case a blank)
indexOf (String searchString)
indexOf (String searchString, int startPosition)
Getting a part of a String
substring (int start, int onecharafterend)
substring (int start)
In code
System.out.println("Enter your name");
String name = sc.nextLine();
int blank = name.indexOf(" ");
String first = name.substring(0,blank);
String last = name.substring(blank+1);
System.out.println("Your first name is " +
first + " and your last is " + last);
Another problem
How many e’s are in your name?
Two solutions:
Use indexOf (starting from the position
after the last e was found)
Use the charAt (int location)
method
Note that charAt returns a character, not a
String. Characters may be tested for
equality, ==, but not Strings
Other string functions
Assume that we have 2 string variables,
first and last
first.equals (last)
Cannot use == with Strings!
first.replace (“e”, “a”)
Replaces all e’s with a’s
last.replaceFirst (“o”, “ww”)
Replaces the first o with ww
One last problem
Determining if a string is an
anagram
How can we solve this?
Summary
Strings are how text gets represented in
Java
String is a built-in class, with lots of
methods associated with it.
Reading Assignment
Media Computation, Chapter 12, Section
2, and pp 435-437