C Programming Strings. Array of characters – most common type of array in C  Let’s make them easier for use Denote the end of array using a special character.

Slides:



Advertisements
Similar presentations
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Advertisements

Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
ECE Application Programming Instructor: Dr. Michael Geiger Spring 2012 Lecture 31: PE5.
1 Strings ( מחרוזות ). 2 Agenda Definition and initialization Termination Input / Output String library.
Introduction to C Programming CE Lecture 13 Strings in C.
To remind us We finished the last day by introducing If statements Their structure was:::::::::
Exercise 10 Review: pointers, strings and recursion.
Exercise 7 Strings. An array of characters Used to store text Another way to initialize: char A[ ]=“blabla”;
Tutorial #8 Summer strings #include int main() { char str1[] = {‘h’,’e’,’l’,’l’,’o’}; char str[] = {‘h’,’e’,’l’,’l’,’o’,’\0’}; char p[] = ”hello”;
Computer Science 210 Computer Organization Strings in C.
PRESENTED BY: ER. SUMANPREET KAUR LECTURER IN CE DEPTT. GPCG ASR.
Strings in C. Strings are Character Arrays Strings in C are simply arrays of characters. – Example:char s [10]; This is a ten (10) element array that.
Chapter 5: Data Input and Output Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
CHAPTER 8 CHARACTER AND STRINGS
Chapter 9 Character Strings 9.1 Character String Constants A character string constant is a sequence of characters enclosed in double quotation mark. Examples.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
Strlen() implementation /* strlen : return length of string s */ int strlen(char *s) { int n; for (n = 0 ; s[n] != ‘\0’ ; n++) ; return n; } /* strlen.
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 13 Strings (Continued)
APS105 Strings. C String storage We have used strings in printf format strings –Ex: printf(“Hello world\n”); “Hello world\n” is a string (of characters)
CS140: Intro to CS An Overview of Programming in C (part 3) by Erin Chambers.
String functions+ string I.Mona Alshehri. String Functions: Header file:#include Function: Int strlen(char s[n]) Description Calculates the length of.
מערכים (arrays) 02 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 1502 דצמבר דצמבר דצמבר 15 1 Department of Computer Science-BGU.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI C-Style Strings Strings and String Functions Dale Roberts, Lecturer.
1 This chapter covers both string constants (or literals, as they're called in the C standard) and string variables, which can change during the execution.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
© Oxford University Press All rights reserved. CHAPTER 6 STRINGS.
Strings Programming Applications. Strings in C C stores a string in a block of memory. The string is terminated by the \0 character:
13. Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal.
Strings, Pointers and Tools
ENEE150 – 0102 ANDREW GOFFIN Strings. Project 2 Flight Database 4 options:  Print flight  Print airport  Find non-stop flights  Find one-stop flights.
Principles of Programming Chapter 8: Character & String  In this chapter, you’ll learn about;  Fundamentals of Strings and Characters  The difference.
1 Pointers: Parameter Passing and Return. 2 Passing Pointers to a Function Pointers are often passed to a function as arguments  Allows data items within.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
Dr. Sajib Datta Feb 21,  In the last class we discussed: ◦ Bubble sort  How it works  performance.
Strings. String Literals String literals are enclosed in double quotes: "Put a disk in drive A, then press any key to continue\n“ A string literal may.
ECE 103 Engineering Programming Chapter 29 C Strings, Part 2 Herbert G. Mayer, PSU CS Status 7/30/2014 Initial content copied verbatim from ECE 103 material.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
© Oxford University Press All rights reserved. Data Structures Using C, 2e Reema Thareja.
Dr. Sajib Datta  Ordering elements in some way  For numeric data, ascending order is the most common  Lots of techniques for sorting  These.
מערכים (arrays) 02 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 1602 אוקטובר אוקטובר אוקטובר 16 Department.
INC 161 , CPE 100 Computer Programming
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
ECE Application Programming
Strings (Continued) Chapter 13
Lecture 8 String 1. Concept of strings String and pointers
C Programming Tutorial – Part I
Strings (מחרוזות).
Strings A string is a sequence of characters treated as a group
Computer Science 210 Computer Organization
Arrays in C.
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
Computer Science 210 Computer Organization
Strings.
INC 161 , CPE 100 Computer Programming
C Programming Strings.
Lecture 11 Strings.
EECE.2160 ECE Application Programming
Your questions from last session
Chapter 8 Character Arrays and Strings
EECE.2160 ECE Application Programming
Exercise Arrays.
Strings in C Array of characters is called a string.
Programming Strings.
EECE.2160 ECE Application Programming
Introduction to Problem Solving and Programming
Presentation transcript:

C Programming Strings

Array of characters – most common type of array in C  Let’s make them easier for use Denote the end of array using a special character  We won’t need to indicate the length each and every time Easier initialization syntax

String Initialization Use a string instead of the usual braces and comma notation char str[] = "Text"; char s[] = "Hello, World!";

String Termination Strings terminate with the special character '\0' (ascii code 0) To hold a string of N characters we need an array of length (at least) N + 1 's''#'' 'f''d''y''4''7''$''_''e''g''d''.''p''H''e''l' 'o'' 'w''o''r''l''d''g''d''.''p''H''e''l' 'o'' 'w''o''r''l''d' '.''p' '\0' Terminator The array The string

String Initialization Use a string instead of the usual braces and comma notation char str[] = "Text"; Shorthand for the longer but equivalent char str[] = {'T', 'e', 'x', 't', '\0'};

String Length int string_length(char str[]) { int i = 0; while (str[i] != '\0') ++i; return i; }

Printing Strings We can use printf to print strings  Use %s to print from the string until '\0'

Printing Strings int main(void) { char str[] = "Hello, World!"; printf("%s\n", str); str[5] = '\0'; printf("%s\n", str); str[10] = '#'; printf("%s\n", str); str[5] = ';'; printf("%s\n", str); return 0; } Hello, World! Hello Hello; Wor#d!

Reading Strings getchar  read character by character scanf  multiple character in a single read  will only read until the first space / newline  scanf("%s", str); NO ‘&’

#define MAXLINE 100 int main(void) { char str[MAXLINE + 1]; /* one more place for the '\0' */ char c; int i = 0; c = getchar(); while (c != '\n' && i < MAXLINE) { str[i] = c; ++i; c = getchar(); } str[i] = '\0'; /* Terminate the string */ printf("The string you entered is: %s\n", str); return 0; } Example – Using getchar()

Reading strings - scanf scanf reads in letters until a space or newline ('\n') is encountered The maximum length can be stated in the parentheses:  scanf("%10s", str);  read 10 characters and terminate with'\0' ( str should be of size at least 11)

Example – using scanf #define MAXLINE 100 int main(void) { char str[MAXLINE + 1]; printf("Please enter a string:\n"); scanf("%100s", str); printf("The string you entered is: %s\n", str); return 0; } Input: fun and games with scanf output: The string you entered is: fun

scanf problem After using scanf the next character that will be read is the space or newline. For example: scanf("%s", str); scanf("%c", &letter); Here letter has the value ‘ ’ or newline (‘\n’).

Solving the problem We need to read and discard the unwanted newline. Either use getchar or inform scanf to expect spaces (also newline) before the next character. scanf("%s", str); scanf(" %c", &tav);

Exercise Implement the function: void replace(char str[], char from, char to); The function replaces every occurrence of the first char with the second one. Write a program to test the above function  read a string from the user (no spaces) and two characters  pass them as arguments to your function  print the result Example  input: “papa” ‘p’ ‘m’  output: “mama”

Solution void replace(char str[], char from, char to) { int i; for (i = 0; str[i] != '\0'; ++i) { if (str[i] == from) str[i] = to; }

Solution #define MAX_STR_LEN 100 int main(void) { char str[MAX_STR_LEN + 1]; char from, to; printf("Please enter a string (no spaces)\n"); scanf("%100s", str); printf(“Character to replace: "); scanf(" %c", &from); printf(“Character to replace with: "); scanf(" %c", &to); replace(str, from, to); printf("The result: %s\n", str); return 0; }

String library Like in the case of stdio.h and math.h, we have a special library for handling strings We should #include

String library All functions assume that a string ends with ‘\0’. Useful functions:  int strlen(char s[]) returns the length of s  int strcmp(char cs[], char ct[]) compares cs with ct  strcpy(char s[], char ct[]) copies the contents of ct to s  strcat(char s[], char ct[]) Concatenate ct to s  and more… see string.h librarystring.h library

Exercise (1) Implement the function void string_swap(char str1[], char str2[]); The function accepts two strings and swaps them.

Solution – string_swap void string_swap(char str1[], char str2[]) { int i = 0, temp, str1_len = strlen(str1), str2_len = strlen(str2); int max; if (str1_len > str2_len) max = str1_len; else max = str2_len; for (i = 0; i <= max; ++i) { temp = str1[i]; str1[i] = str2[i]; str2[i] = temp; }

Exercise (2) Write a program that reads 10 words from the user and sort them.  Use a two-dimensional array to store the words  Use strcmp to compare two words A word is a sequence of characters without spaces of length 20 or less

Sort Reminder set n to number of words to be sorted repeat for counter = 1 to n - 1 do if key[counter] > key[counter+1] then swap the words; end if end do n = n - 1; until n = 1

Solution - main int main(void) { char words[WORDS_NUM][WORD_SIZE + 1]; int i = 0, j = 0; /* read words from user */ for (i = WORDS_NUM; i >= 1; --i) { for (j = 0; j < i - 1; ++j) { if (strcmp(words[j], words[j + 1]) > 0) string_swap(words[j], words[j + 1]); } /* print sorted words */ return 0; }