ITP 342 Mobile App Dev. Strings

Similar documents
Getting started with Java

Full file at

4 Programming Fundamentals. Introduction to Programming 1 1

Variables, Constants, and Data Types

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Lecture 2 Tao Wang 1

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d.

Princeton University. Computer Science 217: Introduction to Programming Systems. Data Types in C

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

IT 374 C# and Applications/ IT695 C# Data Structures

Lexical Structure (Chapter 3, JLS)

Java Basic Datatypees

3 The Building Blocks: Data Types, Literals, and Variables

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

INTRODUCTION 1 AND REVIEW

A variable is a name for a location in memory A variable must be declared

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Input And Output of C++

Sequence of Characters. Non-printing Characters. And Then There Is """ """ Subset of UTF-8. String Representation 6/5/2018.

Working with Strings. Husni. "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

PHP and MySQL for Dynamic Web Sites. Intro Ed Crowley

Babu Madhav Institute of Information Technology, UTU 2015

TCL - STRINGS. Boolean value can be represented as 1, yes or true for true and 0, no, or false for false.

Chapter 2 Working with Data Types and Operators

String Computation Program

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA.

JME Language Reference Manual

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

Chapter 2: Introduction to C++

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

CSc Introduction to Computing

X Language Definition

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

10/9/2012. Computers are machines that process data. assignment in C# Primitive Data Types. Creating and Running Your First C# Program

Visual C# Instructor s Manual Table of Contents

Basic Elements of C. Staff Incharge: S.Sasirekha

UNIT- 3 Introduction to C++

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Full file at

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

We now start exploring some key elements of the Java programming language and ways of performing I/O

Programming for Engineers Introduction to C

4. Inputting data or messages to a function is called passing data to the function.

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Number Systems, Scalar Types, and Input and Output

GraphQuil Language Reference Manual COMS W4115

LECTURE 02 INTRODUCTION TO C++

Chapter 2: Using Data

ML 4 A Lexer for OCaml s Type System

ITP 342 Mobile App Dev. Code

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Swift. Introducing swift. Thomas Woodfin

Language Reference Manual

Chapter 2 Elementary Programming

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Chapter 2, Part I Introduction to C Programming

Chapter 2 Primitive Data Types and Operations

Petros: A Multi-purpose Text File Manipulation Language

Sprite an animation manipulation language Language Reference Manual

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

ARG! Language Reference Manual

Programming in C++ 4. The lexical basis of C++

The C++ Language. Arizona State University 1

Data Types and Variables in C language

2/12/17. Goals of this Lecture. Historical context Princeton University Computer Science 217: Introduction to Programming Systems

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

Lecture 3. Input, Output and Data Types

STUDENT LESSON A7 Simple I/O

My First Command-Line Program

Full file at C How to Program, 6/e Multiple Choice Test Bank

VLC : Language Reference Manual

6.096 Introduction to C++ January (IAP) 2009

Princeton University Computer Science 217: Introduction to Programming Systems The C Programming Language Part 1

printf( Please enter another number: ); scanf( %d, &num2);

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Intro. Scheme Basics. scm> 5 5. scm>

AWK - PRETTY PRINTING

CS1150 Principles of Computer Science Math Functions, Characters and Strings (Part II)

Formatted Output Pearson Education, Inc. All rights reserved.

CMPT 125: Lecture 3 Data and Expressions

PHP. Interactive Web Systems

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Chapter 2. Lexical Elements & Operators

Chapter 2 Primitive Data Types and Operations

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

First Java Program - Output to the Screen

PYTHON- AN INNOVATION

Chapter 2 Primitive Data Types and Operations. Objectives

egrapher Language Reference Manual

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

C: How to Program. Week /Mar/05

Chapter 2: Using Data

"Hello" " This " + "is String " + "concatenation"

Transcription:

ITP 342 Mobile App Dev Strings

Strings You can include predefined String values within your code as string literals. A string literal is a sequence of characters surrounded by double quotation marks ("). let somestring = "Some string literal value" 2

Multiline String Literals If you need a string that spans several lines, use a multiline string literal a sequence of characters surrounded by three double quotation marks. let quotation = """ The White Rabbit put on his spectacles. "Where shall I begin, please your Majesty?" he asked. "Begin at the beginning," the King said gravely, "and go on till you come to the end; then stop." """ 3

Multiline String Literals A multiline string literal includes all of the lines between its opening and closing quotation marks. The string begins on the first line after the opening quotation marks (""") and ends on the line before the closing quotation marks. let singlelinestring = "These are the same." let multilinestring = """ These are the same. """ 4

Multiline String Literals When your source code includes a line break inside of a multiline string literal, that line break also appears in the string s value. If you want to use line breaks to make your source code easier to read, but you don t want the line breaks to be part of the string s value, write a backslash (\) at the end of those lines. let softwrappedquotation = """ The White Rabbit put on his spectacles. "Where shall I begin, \ please your Majesty?" he asked. "Begin at the beginning," the King said gravely, "and go on \ """ 5

Multiline String Literals A multiline string can be indented to match the surrounding code. The whitespace before the closing quotation marks (""") tells Swift what whitespace to ignore before all of the other lines. However, if you write whitespace at the beginning of a line in addition to what s before the closing quotation marks, that whitespace is included. 6

Special Characters in Strings The escaped special characters: \0 (null character) \\ (backslash) \t (horizontal tab) \n (line feed) \r (carriage return) \" (double quotation mark) \' (single quotation mark) let wisewords = "\"Imagination is more important than knowledge\" - Einstein" // "Imagination is more important than knowledge" - Einstein 7

Special Characters in Strings An arbitrary Unicode scalar value, written as \u{n}, where n is a 1 8 digit hexadecimal number let dollarsign = "\u{24}" // $, Unicode scalar U+0024 let blackheart = "\u{2665}" //, Unicode scalar U+2665 let sparklingheart = "\u{1f496}" //, Unicode scalar U+1F496 8

Empty String To create an empty String value as the starting point for building a longer string, either assign an empty string literal to a variable, or initialize a new String instance with initializer syntax. var emptystring = "" // empty string literal var anotheremptystring = String() // initializer syntax // these two strings are both empty, and are equivalent to each other Find out whether a String value is empty by checking its Boolean isempty property. if emptystring.isempty { print("nothing to see here") } // Prints "Nothing to see here" 9

Strings Are Value Types Swift s String type is a value type. If you create a new String value, that String value is copied when it s passed to a function or method, or when it s assigned to a constant or variable. In each case, a new copy of the existing String value is created, and the new copy is passed or assigned, not the original version. Swift s copy-by-default String behavior ensures that when a function or method passes you a String value, it s clear that you own that exact String value, regardless of where it came from. You can be confident that the string you are passed won t be modified unless you modify it yourself. Behind the scenes, Swift s compiler optimizes string usage so that actual copying takes place only when absolutely necessary. This means you always get great performance when working with strings as value types. 10

Concatenating Strings String values can be added together (or concatenated) with the addition operator (+) to create a new String value. let string1 = "hello" let string2 = " there" var welcome = string1 + string2 // welcome now equals "hello there" You can also append a String value to an existing String variable with the addition assignment operator (+=). var instruction = "look over" instruction += string2 // instruction now equals "look over there" 11

String Append You can append a Character value to a String variable with the String type s append() method. let exclamationmark: Character = "!" welcome.append(exclamationmark) // welcome now equals "hello there!" You can append a String to a String variable. let message = "Hello." message.append(" Nice to meet you.") // message equals "Hello. Nice to meet you." 12

String Interpolation String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal. You can use string interpolation in both single-line and multiline string literals. Each item that you insert into the string literal is wrapped in a pair of parentheses, prefixed by a backslash (\). 13

String Interpolation The value of multiplier is inserted into a string literal as \(multiplier). This placeholder is replaced with the actual value of multiplier when the string interpolation is evaluated to create an actual string. The value of multiplier is also part of a larger expression later in the string. This expression calculates the value of Double(multiplier) * 2.5 and inserts the result (7.5) into the string. In this case, the expression is written as \(Double(multiplier) * 2.5) when it s included inside the string literal. let multiplier = 3 let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)" // message is "3 times 2.5 is 7.5" 14

String Interpolation The expressions you write inside parentheses within an interpolated string can t contain an unescaped backslash (\), a carriage return, or a line feed. However, they can contain other string literals. 15

String Indices Each String value has an associated index type, String.Index, which corresponds to the position of each Character in the string. Different characters can require different amounts of memory to store, so in order to determine which Character is at a particular position, you must iterate over each Unicode scalar from the start or end of that String. For this reason, Swift strings can t be indexed by integer values. 16

String Indices Use the startindex and endindex properties. Use the index(before:) and index(after:) methods of String. Use the index(_:offsetby:) method let greeting = "Guten Tag!" greeting[greeting.startindex] // G greeting[greeting.index(before: greeting.endindex)] //! greeting[greeting.index(after: greeting.startindex)] // u let index = greeting.index(greeting.startindex, offsetby: 7) greeting[index] // a 17

String Indices Use the indices property to access all of the indices of individual characters in a string. for index in greeting.indices { print("\(greeting[index]) ", terminator: "") } // Prints "G u t e n T a g! " 18

Inserting To insert a single character into a string at a specified index, use the insert(_:at:) method. To insert the contents of another string at a specified index, use the insert(contentsof:at:) method. var welcome = "hello" welcome.insert("!", at: welcome.endindex) // welcome now equals "hello!" welcome.insert(contentsof: " there", at: welcome.index(before: welcome.endindex)) // welcome now equals "hello there!" 19

Removing To remove a single character from a string at a specified index, use the remove(at:) method. To remove a substring at a specified range, use the removesubrange(_:) method. welcome.remove(at: welcome.index(before: welcome.endindex)) // welcome now equals "hello there" let range = welcome.index(welcome.endindex, offsetby: -6).. <welcome.endindex welcome.removesubrange(range) // welcome now equals "hello" 20

Length of a String Use the count property to determine length. A single string can have greatly differing lengths when measured by its different views. let capitala = "A" print(capitala.count) // Prints "1" let world = " " print(world.count) // Prints "1" print(world.utf16.count) // Prints "2" print(world.utf8.count) // Prints "4" 21

Check for Empty String To check whether a string is empty, use its isempty property instead of comparing the length of one of the views to 0. Unlike with isempty, calculating a view s count property requires iterating through the elements of the string. let empty = "" print(empty.isempty) let full = "I'm full" print(full.isempty) // Prints true // Prints false 22

Changing Case Use the lowercased() method which returns a lowercase version of the string Use the uppercased() method which returns an uppercase version of the string let greeting = "Good Day" print(greeting.lowercased()) // Prints "good day" let warning = "Don't Panic" print(warning.uppercased()) // Prints "DON'T PANIC" 23

Format You can create a string using formats using the init(format: String, CVarArg...) method This returns a String object initialized by using a given format string as a template into which the remaining argument values are substituted. Use % to denote a format specifer let num = 42.20 print("$\(num)") ) // $42.2 let amount = String(format: "$%.2f", num) print(amount) // $42.20 24

Format Specifiers Format depending on the type of variable Specifer Description %% % character %d,%d,%i integer (int) %u,%u unsigned integer %f floating point number (double) %e floating point number in scientific notation %g floating point number in %e or %f 25

Examples Use %f for Float and Double numbers to specify how many digits to display. The first number is the total number of digits and the second number is the number of digits after the decimal point. var num = 42.20 var amount = String(format: "$%.2f", num) print(amount) // $42.20 amount = String(format: "$%6.2f", num) print(amount) // $ 42.20 num = 120.42 amount = String(format: "$%6.2f", num) print(amount) // $120.42 26

Resources https://docs.swift.org/swift-book/ https://developer.apple.com/documentation/s wift/string https://developer.apple.com/library/archive/d ocumentation/cocoa/conceptual/strings/arti cles/formatspecifiers.html 27