Strings 1 Sharif University of Technology Department of Computer - - PowerPoint PPT Presentation

strings
SMART_READER_LITE
LIVE PREVIEW

Strings 1 Sharif University of Technology Department of Computer - - PowerPoint PPT Presentation

Strings 1 Sharif University of Technology Department of Computer Engineering Input and Output Lecture 4 Introduction Until now We have seen strings in printf Our old definition: string is a set of char between


slide-1
SLIDE 1

Sharif University of Technology

Department of Computer Engineering

1

Strings

slide-2
SLIDE 2

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

2

Introduction

  • Until now
  • We have seen strings in printf
  • Our old definition: string is a set of char between “”

printf("This printf("This is a string\n"); is %s\n", "a string\n");

  • Strings:
  • An array of chars
  • Terminated by the null char '\0'
slide-3
SLIDE 3

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

3

Strings in C

  • Since strings are array

char str3[] = {'p', 'r', 'o', 'g', 'r', 'a', 'm', '\0'}; str1[8] = "program"; char char str2[] = "program";

'p' 'r' 'o' 'g' 'r' 'a' 'm' '\0'

slide-4
SLIDE 4

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

4

String

  • Initializing char array ...

– char s[10] = "unix"; /* s[4] is '\0'; */ – char s[ ] = "unix"; /* s has five elements */

slide-5
SLIDE 5

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

5

Strings are Character Arrays

  • Strings in C are simply arrays of characters

– Example: char s [10];

  • This is a ten (10) element array that can hold a character

string consisting of  9 characters

  • This is because C does not know where the end of an array

is at run time

– By convention, C uses a NULL character '\0' to terminate all strings in its library functions

  • For example:

char str [10] = {'u', 'n', 'I', 'x', '\0'};

  • It’s the string terminator (not the size of the array) that

determines the length of the string

slide-6
SLIDE 6

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

6

  • Each character has an integer representation

Strings

a b c d e z … … … … 97 98 99 100 101 ………………………112 A B C D E Z … … … … 65 66 67 68 69 ……………………… 90 1 2 3 4 9 8 7 6 5 48 49 50 51 52 53 54 55 56 57 \0 \n 10

slide-7
SLIDE 7

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

7

Accessing Individual Characters

  • The first element of any array in C is at index 0. The second

is at index 1, and so on ...

char s[10]; s[0] = 'h'; s[1] = 'i’; s[2] = '!'; s[3] = '\0';

  • This notation can be used in all kinds of statements and

expressions in C:

– For example:

c = s[1]; if (s[0] == '-') … switch (s[1]) ...

? ? ? ? ? ? \0 ! i h [9] [8] [7] [6] [5] [4] [3] [2] [1] [0] s

slide-8
SLIDE 8

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

8 8

  • Characters can be interpreted as integers

char c = ‘A’; printf(“%c \n”,c); prints A printf(“%d \n”,c); prints 65 Printf(“%c \n”,65); prints A

Strings

slide-9
SLIDE 9

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

9

Reading & Writing Strings

  • printf can be used to print strings

printf("program"); printf("%s", "program");

  • scanf can be used to read strings

char str[200]; scanf("%s", str);

  • Note: No ampersand(&) when inputting strings into character

arrays!

  • Initial white spaces are ignored
  • Read until white space (which is replaced by \0)
  • We must allocate sufficient size
slide-10
SLIDE 10

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

10

Example

char str[11]="unix and c"; printf("%s", str); printf("\n"); str[6]='\0'; printf("%s", str); printf("\n"); printf("\n"); printf(str); printf("\n"); str[2]='I'; printf(str); printf("\n");

\0 c d n a x i n u [10] [9] [8] [7] [6] [5] [4] [3] [2] [1] [0] str \0 c d \0 a x i n u [10] [9] [8] [7] [6] [5] [4] [3] [2] [1] [0] str \0 c d \0 a x I n u [10] [9] [8] [7] [6] [5] [4] [3] [2] [1] [0] str

slide-11
SLIDE 11

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

11

Exercise

  • Write a function to count the number of characters in a string.
  • Idea: count the number of characters before \0

H e l l

  • \0
slide-12
SLIDE 12

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

12

Solution

int count_letters(char cdata[]) { int i=0; while (cdata[i] != '\0') i = i + 1; return(i); }

slide-13
SLIDE 13

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

13

Exercise

  • Write a function that prints a string in reverse
  • Idea: find the end of the string and print the characters

backwards.

H e l l

  • \0

Output: olleH

slide-14
SLIDE 14

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

14

Solution

void print_reverse(char pdata[]) { int size,position; size = count_letters(pdata); position = size - 1; while (position >= 0) { printf("%c",pdata[position]); position = position -1; } printf("\n"); return; }

slide-15
SLIDE 15

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

15

Exercise

  • Write a function that compares 2 strings S1 and S2 using

lexicographic order.

  • Idea: compare character by character
  • Return

– a neg value if S1 < S2, – 0 if S1 == S2 – a pos value if S1 > S2

H e l l

  • \0

H e l

  • \0

l < o in lexicographic order

slide-16
SLIDE 16

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

16

Solution (incomplete)

int compare(char cdata1[], char cdata2[]) { int i= 0; while (cdata1[i] == cdata2[i]) i = i + 1; return (cdata1[i] - cdata2[i]); }

slide-17
SLIDE 17

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

17

Solution (complete)

int compare(char cdata1[], char cdata2[]) { int i= 0; while (cdata1[i] != ‘\0’ && cdata2[i] != ‘\0’ && cdata1[i] == cdata2[i]) i = i + 1; return (cdata1[i] - cdata2[i]); }

slide-18
SLIDE 18

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

18

Exercise: Spell out a number in text using arrays of strings

  • Write a program that reads a number

between 1 and 999 from user and spells out it in English. For example:

  • 453

 Four hundred fifty three

  • 37  Thirty seven
  • 204

 Two hundred four

slide-19
SLIDE 19

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

19

Reading & Writing Strings (cont’d)

  • puts(str)is very simple version of printf
  • Can only be used to print strings
  • Adds ‘\n’ to end of string
  • Prototype of puts is defined in stdio.h

– This is more efficient than printf : because your program doesn't need to analyze the format string at run-time. – For example:

char sentence[] = "The quick brown fox"; puts(sentence); // printf("The quick brown fox\n");

slide-20
SLIDE 20

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

20

Reading & Writing Strings (cont’d)

  • Gets (str)can be used to read strings
  • Gets does not ignore the white spaces
  • Read until \n
slide-21
SLIDE 21

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

21

Difference between gets and scanf

  • gets( ) read a line
  • scanf("%s",…) read up to the next space

char line[80]; char line[80]; gets(line); scanf("%[ ^\n]s", line); puts(line); printf(“%s\n", line);

slide-22
SLIDE 22

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

22

String Library

  • Access to string library by

#include <string.h>

  • Many functions to work with strings
  • Find the length of string
  • Compare strings
  • Copy strings
  • Search in strings
  • Concatenating strings
slide-23
SLIDE 23

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

23

Length of String

  • strlen(str): Length of string
  • From start to first occurrence of the null char

str[] = "This is test"; char char str1[10]={'a', 'b', '\0', 'c', '\0'}; strlen(str)  12 strlen(str1)  2

slide-24
SLIDE 24

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

24

Compare Strings

  • str1 and str2 are compared as follows
  • Compare char by char from left to right until str1 and

str2 has same chars.

  • In the first different char
  • If(char of str1 < char of str2)  str1 < str2
  • If (both string finish)  str1 = str2
  • strcmp(str1, str2):compare str1 and str2
  • If(str1 == str2)  return 0
  • If(str1 < str2)  return -1
  • If(str1 > str2)  return 1
slide-25
SLIDE 25

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

25

Compare Strings: Examples

char s1[] = "abc"; char s2[] = "abc"; i = strcmp(s1, s2); //i = 0 char s3[] = "abc"; char s4[] = "abx"; i = strcmp(s3, s4); //i = -1 char s5[] = "axc"; char s6[] = "abc"; i = strcmp(s5, s6); //i = 1 char s7[] = "ab"; char s8[] = "abc"; i = strcmp(s7, s8); //i = -1 char s9[] = "abc"; char s10[] = "aBc"; i = strcmp(s9, s10); //i = 1

slide-26
SLIDE 26

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

26

Compare Strings

  • strcmpi(str1, str2)
  • Compares str1 and str2 similar to strcmp
  • But ignores uppercase/lowercase

difference

char str1[]="ABC", str2[]="abC"; strcmpi(str1, str2)  0

slide-27
SLIDE 27

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

27

strncmp

int strncmp (char *str1, char * str2, size_t n);

– Compares n chars of str1 and str2

  • Continues until n chars are compared or
  • The end of str1or str2 is encountered
slide-28
SLIDE 28

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

28

Example

char str1[] = "The first string."; char str2[] = "The second string."; printf("%d\n", strcmp(str1,str2) ); // -1 printf("%d\n", strncmp(str1,str2,4) ); // 0 // 'f' - 's' = -13 printf("%d\n", strncmp(str1,str2,5) ); // -13 If(str1 == str2) … // Syntax error in many c complier!

slide-29
SLIDE 29

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

29

strcpy

  • Copying a string comes in the form:

char *strcpy (char * destination, char * source);

  • A copy of source is made at destination

– source should be NULL terminated – destination should have enough room (its length should be at least the size of source)

slide-30
SLIDE 30

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

30

Copy Strings: Example

char str1[] = "Test String"; char str2[20]; strcpy(str2, str1); printf("%s\n", str2); printf("%s\n", str1); Test String Test String

slide-31
SLIDE 31

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

31

strcat

  • Concatenating two stings:

char * strcat (char * str1, char * str2);

–Appends a copy of str2 to the end of str1

  • Ensure that str1 has sufficient space for the

concatenated string!

– Array index out of range will be the most popular bug in your C programming career

slide-32
SLIDE 32

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

32

Concatenate Strings: Example

char str1[] = "String"; char str2[20]= "Test "; strcat(str2, str1); printf("%s\n", str2);

Test String

slide-33
SLIDE 33

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

33

Example

#include <string.h> #include <stdio.h> int main() { char str1[10] = "abc"; char str2[100]; printf("%d\n", strlen(str1)); strcpy(str2, str1); puts(str2); puts("\n"); // printf("\n\n"); strcat(str2, str1); puts(str2); }

slide-34
SLIDE 34

Input and Output – Lecture 4

Sharif University of Technology

Department of Computer Engineering

34

Common Bugs & Avoiding them

  • Strings which are used as destination
  • scanf, strcpy, ….
  • Must be large enough

Take care about the ‘\0’

  • You should never destroy it!