C Programming Strings. Mrs. Hajah T. Sueno, MSIT instructor

Similar documents
ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Stacks. Linear data structures

C Strings and Pointers

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

Sources: On the Web: Slides will be available on:

CS106A, Stanford Handout #38. Strings and Chars

5 Arrays and Pointers

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Basics of I/O Streams and File I/O

Install Java Development Kit (JDK) 1.8

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

Variables, Constants, and Data Types

6.170 Tutorial 3 - Ruby Basics

So far we have considered only numeric processing, i.e. processing of numeric data represented

Chapter 13 - The Preprocessor

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Python Lists and Loops

Informatica e Sistemi in Tempo Reale

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

1 Description of The Simpletron

Chapter 2: Elements of Java

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

03 - Lexical Analysis

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Lexical analysis FORMAL LANGUAGES AND COMPILERS. Floriano Scioscia. Formal Languages and Compilers A.Y. 2015/2016

Passing 1D arrays to functions.

Semantic Analysis: Types and Type Checking

The C Programming Language course syllabus associate level

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Software security. Buffer overflow attacks SQL injections. Lecture 11 EIT060 Computer Security

Introduction to Programming II Winter, 2014 Assignment 2

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Chapter 7 Assembly Language

An Introduction to Assembly Programming with the ARM 32-bit Processor Family

Lecture 5: Java Fundamentals III

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Introduction to Python

J a v a Quiz (Unit 3, Test 0 Practice)

X86-64 Architecture Guide

Programming Languages CIS 443

Java Interview Questions and Answers

arrays C Programming Language - Arrays

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Some Scanner Class Methods

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

Introduction to Programming

C++ Language Tutorial

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Number Representation

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Explain the relationship between a class and an object. Which is general and which is specific?

Lecture 9. Semantic Analysis Scoping and Symbol Table

Computer Science Questions and Answers UNIT-A Chapter - 1 Configuring a Computer

Introduction to Information Security

Member Functions of the istream Class

1 Abstract Data Types Information Hiding

Java Basics: Data Types, Variables, and Loops

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Performing Simple Calculations Using the Status Bar

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Compilers Lexical Analysis

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

LC-3 Assembly Language

20 Using Scripts. (Programming without Parts) 20-1

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

C PROGRAMMING FOR MATHEMATICAL COMPUTING

Chapter 13 Storage classes

CS 106 Introduction to Computer Science I

As previously noted, a byte can contain a numeric value in the range Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets!

Symbol Tables. Introduction

Introduction to Java. CS 3: Computer Programming in Java

C++ INTERVIEW QUESTIONS

Chapter 7: Additional Topics

Development of a Campus Routing System Praxis der Software-Entwicklung

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

Module 816. File Management in C. M. Campbell 1993 Deakin University

Chapter 3. Input and output. 3.1 The System class

public static void main(string[] args) { System.out.println("hello, world"); } }

3.GETTING STARTED WITH ORACLE8i

PROC SQL for SQL Die-hards Jessica Bennett, Advance America, Spartanburg, SC Barbara Ross, Flexshopper LLC, Boca Raton, FL

The programming language C. sws1 1

Moving from CS 61A Scheme to CS 61B Java

Unit 6. Loop statements

Chapter 5 Names, Bindings, Type Checking, and Scopes

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Application Security: Web service and

C++ Programming Language

Using Regular Expressions in Oracle

Q&As: Microsoft Excel 2013: Chapter 2

Computer Programming Tutorial

Computer Programming C++ Classes and Objects 15 th Lecture

VB.NET - STRINGS. By calling a formatting method to convert a value or object to its string representation

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Chapter 4: Computer Codes

Transcription:

C Programming Strings Mrs. Hajah T. Sueno, MSIT instructor

String Basics

3 Characters Characters are small integers (0-255) Character constants are integers that represent corresponding characters. 0 48 A 65 \0 (NULL) 0 \t (TAB) 9 \n (newline) 10 SPACE 32

4 Strings(1) String a group of characters C implements the string data structure using arrays of type char. Two things to remember 1. All strings have a hidden extra character at the end \0, the null character. Hello is a string of length 6 2. Strings are managed by pointers char *s = Hello ; Creates a pointer s such that H e l l o \0 S

5 Strings(2) Two interpretations of String Arrays whose elements are characters. Pointer pointing to characters. Strings are always terminated with a NULL characters( \0 ). C needs this to be present in every string so it knows where the string ends. char a[] = hello\n ; char* b = hello\n ; a[0] a[1] a[2] a[3] a[4] a[5] a[6] *b *(b+1) *(b+2) *(b+3) *(b+4) *(b+5) *(b+6) h e l l o \n null 104 101 108 108 111 10 0

6 String Constants We have already used string constants extensively in our earlier work: printf( Hello There ); Hello There is a string constant In C, string constants are identified by surrounding Note that this is different from characters they use single quotes Spaces are just treated like any other character A null character is automatically inserted after the constant string. You can also use #define directive to associate a symbolic name with a string constant. #define ERR ***ERROR***

7 Initializing and Declaring String char s[] = hello ; char* s_ptr = hello ; char s[] = { h, e, l, l, o, \0 }; We can leave out the dimension of the array, the compiler can compute it automatically based on the size of the string (including the terminating \0). String Declaration char s[30]; // declared as an array of 30 char char *s; // declared as a pointer to char Note that the array s actually holds 30 characters, but the string can only contain up to 29. Because the 30th character would be \0.

8 Input/Output with printf and scanf Both printf and scanf can handle string arguments as long as the placeholder %s is used in the format string: char s[] = hello ; printf( %s\n, s); The printf function, like other standard library functions that take string arguments, depends on finding a null character in the character array to mark the end of the string.

9 Input/Output Cont. The approach scanf takes to string input is very similar to its processing of numeric input. When it scans a string, scanf skips leading whitespace characters such as blanks, newlines, and tabs. Starting with the first non-whitespace character, scanf copies the characters it encounters into successive memory cells of its character array argument. When it comes across a whitespace character, scanning stops, and scanf places the null character at the end of the string in its array argument. char s[10]; scanf( %s, s); // bad practice scanf( %9s, s); // Good practice, prevents overflowing s Notice that there is no &, this is because strings are arrays, and arrays are already pointers.

String Library Functions

11 Assignment and Substrings We used assignment operator = to copy data into variable. We used assignment symbol in declaration of string variable. Copy string that is in the right operand into the variable that is in the left operand. Array name with no subscript represents the address of the initial array element

12 Assignment and Substrings char str[20]; str = Test String ; // Does not work Compiler error message such as Invalid target of assignment.

13 String Library Functions C provides functions to work with strings, these are located in the string.h file. Put #include <string.h> at the top of the program to use these. Note that all of these function expect the strings to be null terminated.

14 strlen() function Syntax: len = strlen(ptr); where len is an integer and ptr is a pointer to char strlen() returns the length of a string, excluding the null. The following code will result in len having the value 13. int len; char str[15]; strcpy(str, "Hello, world!"); len = strlen(str);

15 Example #include < stdio.h > #include < string.h > void main() { char name[100]; int length; printf( Enter the string ); gets(name); length=strlen(name); printf( \The string length is=%d,length); }

16 strcpy() function Syntax: strcpy(ptr1, ptr2); where ptr1 and ptr2 are pointers to char strcpy() is used to copy a null-terminated string into a variable. Given the following declarations, several things are possible.

17 strcpy() function char S[25]; char D[25]; Putting text into a string: strcpy(s, "This is String 1."); Copying a whole string from S to D: strcpy(d, S); Copying the tail end of string S to D: strcpy(d, &S[8]);

18 strcpy() function We typically use the assignment operator = to copy data into a variable. char c, s[10]; c = a ; s = Hello ; // Does not work, Why? Exception: we can use the assignment symbol in a declaration of a string variable with initialization. char s[] = hello ;

19 strcpy() function C does not allow you to assign the characters to a string directly as in the statement name= Robert ; Instead use the strcpy strcpy(string1,string2);

20 strcpy() function strcpy function assigns the contents of string2 to string1. string2 may be a character array variable or a string constant. In all other cases, you must do s[0] = H s[1] = e s[2] = l // etc Or use string copy function.

21 strncpy() function Syntax: strncpy(ptr1, ptr2, n); where n is an integer and ptr1 and ptr2 are pointers to char strncpy() is used to copy a portion of a possibly null-terminated string into a variable. Care must be taken because the '\0' is put at the end of destination string only if it is within the part of the string being copied. Function strncpy copies upto n characters of the source string to the destination.

22 strncpy() function char source[25]; char destination[25]; Assume that the following statement has been executed before each of the remaining code fragments. Putting text into the source string: strcpy(source, "This is String 1."); Copying four characters from the beginning of S to D and placing a null at the end: strncpy(destination, source, 4); destination[4] = '\0';

23 strncpy() function Copying two characters from the middle of string source to destination: strncpy(destination, &source[5], 2); destination[2] = '\0'; Copying the tail end of string source to destination: strncpy(destination, &source[8], 15); which produces the same result as strcpy(destination, &source[8]);

24 strcat() function Syntax: strcat(ptr1, ptr2); where ptr1 and ptr2 are pointers to char strcat() is used to concatenate a nullterminated string to end of another string variable. This is equivalent to pasting one string onto the end of another, overwriting the null terminator. There is only one common use for strcat().

25 strcat() function when you combine two strings, you add the characters of one string to the end of other string. This process is called concatenation. The strcat() function joins 2 strings together. char s1[25] = "world!"; char d1[25] = "Hello, "; Concatenating the whole string s1 onto d1: strcat(d1, s1);

26 strcat() function //another example of concatenating string strcpy(string1,"crying "); strcpy(string2,"baby"); printf("%s",strcat(string1,string2));

27 strncat() function Syntax: strncat(ptr1, ptr2, n); where n is an integer and ptr1 and ptr2 are pointers to char strncat() is used to concatenate a portion of a possibly null-terminated string onto the end of another string variable. Care must be taken because some earlier implementations of C do not append the '\0' at the end of destination string.

28 strncat() function Given the following declarations, several things are possible, but only one is commonly used. char s1[25] = "world!"; char d2[25] = "Hello, "; Concatenating five characters from the beginning of S onto the end of D and placing a null at the end: strncat(d2, s1, 5); strncat(d2, s1, strlen(s1) -1); Both would result in d2 containing "Hello, world".

29 Laboratory Exercise Problem Write a program that takes data a line at a time and reverse the words of the line. For example: Input: birds bees Reversed: bees and birds

30 strcmp() function Syntax: diff = strcmp(ptr1, ptr2); where diff is an integer and ptr1 and ptr2 are pointers to char Most libraries however contain the strcmp() function, which returns a zero if 2 strings are equal, or a non zero number if the strings are not the same.

31 strcmp() function strcmp(string1,string2) ; String1 & string2 may be string variables or string constants. String1, & string2 may be string variables or string constants some computers return a negative if the string1 is alphabetically less than the second and a positive number if the string is greater than the second.

32 strcmp() and strncmp () function /*diff will have a negative value after the following statement is executed.*/ diff = strcmp(str1,str2); //strcmp(cat,cut) printf("%d",diff); //strncmp diff = strncmp(str1,str2,2); printf("%d",diff);

33 strcmp() function /*diff will have a positive value after the following statement is executed.*/ diff = strcmp(str2,str1); //strcmp(cut,cat) printf("%d",diff); //strncmp diff = strncmp(str2,str1,3); printf("%d",diff);

34 strcmp() function /*diff will have a value of zero (0) after the execution of the following statement, which compares s1 with itself. */ diff = strcmp(str1,str1); printf("%d",diff); //strncmp diff = strncmp(str1,str2,1); printf("%d",diff);

35 strcmpi() function This function is same as strcmp() which compares 2 strings but not case sensitive. Example strcmpi( THE, the ); //will return 0.

36 strlwr () function This function converts all characters in a string from uppercase to lowercase. Syntax: strlwr(string); For example: strlwr( SYSTEMS ) ; //converts to systems.

37 strrev() function This function reverses the characters in a string. Syntax: strrev(string); For ex strrev( program ); /*reverses the characters in a string into margrop. */

38 strupr() function This function converts all characters in a string from lower case to uppercase. Syntax: strupr(string); ex. strupr( program ); //PROGRAM

39 NEXT: Group Activity

40 Substring Extraction We frequently need to reference a substring of a longer string. For example we might want to examine the Cl in the string NaCl. We can use strncpy to copy a middle or an ending portion of a string. strncpy(dest, &source[2], 2);

41 Substring Extraction This goes to the 3rd spot in the array source, gets the memory location, and then copies 2 elements starting at this new memory location. Function strstr finds the first occurrence of one string inside another. char* strstr(char *s_in, char *s_for) Returns a pointer to the first location in s_in where s_for appears. Returns NULL if not found. Case sensitive.

42 String Comparison Will string_1 < string_2 work? int strcmp(char *s1, char *s2) Wrong! they are only pointers Compares two strings lexicographically (based on ASCII code). Returns 0 if they are same Returns negative if s1< s2 Returns positive if s1> s2 int strncmp(char *s1, char *s2, int n) Compares two strings upto n characters.

43 String Comparison How to compare and swap two strings: if (strcmp(s1, s2) > 0){ strcpy(tmp, s1); strcpy(s1, s2); strcpy(s2, tmp); }

44 String Concatenation Concatenation is taking two strings and then make them become one string. char* strcat(char *dest, char *src) Puts src at the end of dest, including src s null terminator. Puts the first character of src in place of dest s null terminator. Reurns pointer to the old value of dest.

45 String Concatenation strncat does the same as strcat, but it only copies n characters from the second string strncat(s1, s2,3); would copy only 3 character from s2. Puts a null terminator at the end of dest when it is done copying. In both cases, overflowing is possible and as a result we may overwrite other variables or get a run-time error.

46 Summary The two most important questions dealing with strings are the following: 1. Is there enough room to perform the given operation? 2. Does the created string end in \0? When we write our own string-building functions, we must be sure that a null character is inserted at the end of every string. This inclusion of the null character is automatic for constant string. The caller of a string function must provide space into which the called function can store its result. Proper behavior is entirely dependent on the availability of adequate space in the output parameter even though the called function does not require the user to provide this size as an input argument.

47 Group Exercises