Download presentation
Presentation is loading. Please wait.
Published byJasmine Moore Modified over 9 years ago
1
CSC1401 Strings (text)
2
Learning Goals Working with Strings as a data type (a class) Input and output of Strings String operations
3
Strings Anything within double quotes Examples: System.out.println(“Hi”); System.out.println(“The amount is “ + money); String name = “Steve”;
4
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”;
5
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(); …
6
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
7
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??? …
8
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)
9
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);
10
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
11
Other string functions Assume that we have 2 string variables, first and last first.equals (last) Cannot use == with String s! first.replace (“e”, “a”) Replaces all e’s with a’s last.replaceFirst (“o”, “ww”) Replaces the first o with ww
12
One last problem Determining if a string is an anagram How can we solve this?
13
Summary Strings are how text gets represented in Java String is a built-in class, with lots of methods associated with it.
14
Reading Assignment Media Computation, Chapter 12, Section 2, and pp 435-437
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.