Strings CSE 1310 – Introduction to Computers and Programming

Slides:



Advertisements
Similar presentations
Java Programming Strings Chapter 7.
Advertisements

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Hand Crafting your own program By Eric Davis for CS103.
C++ Data Type String A string is a sequence of characters enclosed in double quotes. Examples of strings: “Hello” “CIS 260” “Students” The empty string.
Introduction to Computer Programming Stringing Along – Using Character and String Data.
03 Data types1June Data types CE : Fundamental Programming Techniques.
The Class String. String Constants and Variables  There is no primitive type for strings in Java.  There is a class called String that can be used to.
CS 180 Recitation 8 / {30, 31} / Announcements Project 1 is out –Due 10:00pm –Start early! –Use the newsgroup for your questions –LWSN B146.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
PHP : Hypertext Preprocessor
Integer Division What is x? int x = 1729 / 100; Answer: 17.
Methods (Functions) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Mastering Char to ASCII AND DOING MORE RELATED STRING MANIPULATION Why VB.Net ?  The Language resembles Pseudocode - good for teaching and learning fundamentals.
Introduction to Java Thanks to Dan Lunney (SHS). Java Basics File names The “main” method Output to screen Escape Sequence – Special Characters format()
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
Getting Started with Java Recitation – 1/23/2009 CS 180 Department of Computer Science, Purdue University.
Files CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Objects and Classes; Strings. 2 Classes and objects class: A program entity that represents either 1.A program / module, or 2.A type of objects* –A class.
1 Text processing. 2 text processing: Examining, editing, formatting text.  Text processing often involves for loops that examine the characters of a.
Arrays and Array Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 4 Mathematical Functions, Characters,
EXAM 1 REVIEW. days until the AP Computer Science test.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
First Programs CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) public static void main(String[]
Introduction to Programming
CMSC 202 Java Console I/O. July 25, Introduction Displaying text to the user and allowing the user to enter text are fundamental operations performed.
CSC1401 Strings (text). Learning Goals Working with Strings as a data type (a class) Input and output of Strings String operations.
String and Scanner CS 21a: Introduction to Computing I First Semester,
Chapter 3: Classes and Objects Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Java’s String Class.
CHAPTER 5 GC 101 Input & Output 1. INTERACTIVE PROGRAMS  We have written programs that print console output, but it is also possible to read input from.
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
Strings Mr. Smith AP Computer Science A. What are Strings? Name some of the characteristics of strings: A string is a sequence of characters, such as.
C++ String Class nalhareqi©2012. string u The string is any sequence of characters u To use strings, you need to include the header u The string is one.
Formatted Output (printf) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
 CSC111 Quick Revision. Problem Write a java code that read a string, then show a list of options to the user to select from them, where:  L to print.
Strings and I/O. Lotsa String Stuff… There are close to 50 methods defined in the String class. We will introduce several of them here: charAt, substring,
Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Computer Programming 2 Lab (1) I.Fatimah Alzahrani.
C OMMON M ISTAKES CSC Java Program Structure  String Methods.
import java.util.Scanner; class myCode { public static void main(String[] args) { Scanner input= new Scanner(System.in); int num1; System.out.println(“Enter.
Formatted Output (printf) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Arrays and Array Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Decisions (If Statements) And Boolean Expressions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington.
Common Mistakes with Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Strings A String is a sequence of letters
Strings CSE 1310 – Introduction to Computers and Programming
Strings CSE 1310 – Introduction to Computers and Programming
Strings CSE 1310 – Introduction to Computers and Programming
Boolean Expressions and Conditionals (If Statements)
CSCI 161 – Introduction to Programming I William Killian
Formatted Output (printf)
Exceptions and User Input Validation
First Programs CSE 1310 – Introduction to Computers and Programming
OUTPUT STATEMENTS GC 201.
INPUT STATEMENTS GC 201.
Common Mistakes with Functions
Methods (Functions) CSE 1310 – Introduction to Computers and Programming Alexandra Stefan and Vassilis Athitsos University of Texas at Arlington.
Introduction to Computer Science and Object-Oriented Programming
Array Lists CSE 1310 – Introduction to Computers and Programming
Decisions (If Statements) And Boolean Expressions
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
Exam Prep.
First Programs CSE 1310 – Introduction to Computers and Programming
More on iterations using
Input and Formatted Output (printf)
Presentation transcript:

Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington

Summary String type, String objects Concatenation: + Escape sequences: \\, \n (vs %n), \t, \" Methods: length, charAt, indexOf, Discuss signature and method call int len = "hello".length(); // len is now 5 char c = "hello".charAt(1); // c is 'e' int idx = "hello".indexOf("ll"); // idx is now2 Null Strings Error: Index out of bound See line number with the error Do not use == to compare strings! Use compareTo next() vs nextLine() Substring Substring vs char

Problems Solving problems: User enters name, print initial: Alexandra -> A User enters name, correct it: alexandra stefan-> Alexandra Stefan Horoscope: Recognize if a date is under a specific sign (e.g. Leo) Recognize if a string has a date format. Discuss: assumptions, test cases

The String Type In the same way that int and double are designed to store numerical values, the String type is designed to store text. Text for strings must be enclosed in double quotes. Examples: String name = "George"; String phone_number = "310-123-987";

A Simple Program Using Strings import java.util.Scanner; public class example1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.printf("Hi, my name is Java.\n"); System.out.printf("What is your first name? "); String first_name = in.next(); System.out.printf("What is your last name? "); String last_name = in.next(); System.out.printf("Hello %s %s, nice to meet you!\n", first_name, last_name); } Example Output: Hi, my name is Java. What is your first name? Mary What is your last name? Smith Hello Mary Smith, nice to meet you!

String Input from the User import java.util.Scanner; public class example1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.printf("Hi, my name is Java.\n"); System.out.printf("What is your first name? "); String first_name = in.next(); System.out.printf("What is your last name? "); String last_name = in.next(); System.out.printf("Hello %s %s, nice to meet you!\n", first_name, last_name); } As you see above, to read a string from user input, you use the Scanner.next() method. Note: although the code calls in.next(), the name of the method is Scanner.next(), because in is just an arbitrary variable name.

Length of a String import java.util.Scanner; public class example1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.printf("Hi, my name is Java.\n"); System.out.printf("What is your name? "); String name = in.next(); int length = name.length(); System.out.printf("Your name has %d letters!\n", length); } Example Output: Hi, my name is Java. What is your name? Vassilis Your name has 8 letters! To obtain the length of a string, we use the String.length() method.

String Concatenation Using + import java.util.Scanner; public class example1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.printf("What is your first name? "); String first_name = in.next(); System.out.printf("What is your last name? "); String last_name = in.next(); String name = first_name + last_name; System.out.printf("Hello %s!\n", name); } Example Output: What is your first name? Mary What is your last name? Smith Hello MarySmith! string1 + string2 returns the result of putting those strings together. We call this string concatenation.

String Concatenation Using + import java.util.Scanner; public class example1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.printf("What is your first name? "); String first_name = in.next(); System.out.printf("What is your last name? "); String last_name = in.next(); String name = first_name + " " + last_name; System.out.printf("Hello %s!\n", name); } Example Output: What is your first name? Mary What is your last name? Smith Hello Mary Smith! When you concatenate strings, make sure that you put spaces where they are needed.

Escape Sequences If you want to put a " character in a string: use \" If you want to put a newline character in a string: use \n public class example1 { public static void main(String[] args) { String a = "He said \"Hello\""; String b = "C:\\users\\jane\\note.txt"; String c = "*\n**\n***"; System.out.println(a); System.out.println(b); System.out.println(c); } Output: He said "Hello" C:\users\jane\note.txt * ** ***

Escape Sequences In order to print Use: Code example Output " \" \ \\ System.out.println("He said \"Hello\""); He said "Hello" \ \\ System.out.println("C:\\users\\jane"); C:\users\jane % \% System.out.println("Exams are 75\%."); Exams are 75%. newline \n System.out.println("*\n**\n***"); * ** ***

Characters and Substrings The position of string characters are numbered starting from 0. To get the character at position p: use charAt(p); To get the substring from position s up to and not including position t, use substring(s, t) H e l o , w r d ! 1 2 3 4 5 6 7 8 9 10 11 12 Index public class example1 { public static void main(String[] args) { String str = "Hello, world!"; char first = str.charAt(0); char fifth = str.charAt(4); String sub = str.substring(2, 9); System.out.println(first); System.out.println(fifth); System.out.println(sub); } Output: H o llo, wo

Characters and Substrings IndexOutOfBoundsException Error Valid indexes = indexes corresponding to characters in the string. If you try to grab a character from an invalid index for the given string you get an IndexOutOfBoundsException, explained as: String index out of range: badIndex H e l o , w r d ! 1 2 3 4 5 6 7 8 9 10 11 12 Index String str = "Hello, world!"; char bad1 = str.charAt(-2); // String index out of range: -2 char bad2 = str.charAt(13); // String index out of range: 13 String subBad1 = s.substring(8,16); // String index out of range: 16 Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -2 at java.lang.String.charAt(String.java:646) at TryOutErase.main(TryOutErase.java:5) Java Result: 1 5 is the number of line in your code that produced the error.

indexOf indexOf returns the index of the first occurrence of a substring in another string Returns: -1 if there is no occurrence and the index if found, H e l o , w r d ! 1 2 3 4 5 6 7 8 9 10 11 12 Index public class example1 { public static void main(String[] args) { String str1 = "Hello, world!"; int idx1 = str1.indexOf("or"); // found, starts at index 8 int idx2 = str1.indexOf("old"); // not found: -1 int idx3 = str1.indexOf("o"); // index of first o System.out.println("idx1 = " + idx1); System.out.println("idx2 = " + idx2); System.out.println("idx3 = " + idx3); } Output: idx1 = 8 idx2 = -1 idx3 = 4

Printing Characters with printf To print a value of type char with System.out.printf, you can use either %s or %c (they both work).

Example 1: Printing Name Initial Write a program that: Asks the user: What is your name? Gets the name from user input. Prints: Your initial is X where X is the first letter of the name that the user typed.

Example 1: Printing Name Initial import java.util.Scanner; public class example1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.printf("What is your name? "); String name = in.next(); char initial = name.charAt(0); System.out.printf("Your initial is %s\n", initial); } Example Output: What is your name? Mary Your initial is M Example Output: What is your name? John Your initial is J

Practice: Capitalize name Write a program that: Asks the user: What is your full name? Gets the name from user input. “extracts” the first and last names Prints them afterward Asks the user: What is your full name? Fixes the name to make each part start with a capital letter E.g. user enters alex stefan and the program prints Alex Stefan Hint: find intermediary steps to go from the above problem to this one.

Extra material

String Concatenation Using += import java.util.Scanner; public class example1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); String message = "Hello "; System.out.printf("What is your first name? "); String first_name = in.next(); message += first_name; System.out.printf("%s!\n", message); } Example Output: What is your first name? Mary Hello Mary! The following two lines do the EXACT SAME THING: variable_name += value; variable_name = variable_name + value;