Strings.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
Lecture 09 Strings, IDEs. METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet Sacan Mon July 29, 2002.
Character String Manipulation. Overview Character string functions sscanf() function sprintf() function.
Character String Manipulation. Overview Character string functions sscanf() function snprintf() function.
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.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Characters and Strings.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Fundamentals of Strings and Characters Characters.
Introduction to Computers and Programming Class 22 Character Arrays (Strings) Professor Avi Rosenfeld.
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.
C Arrays and Pointers In Java, pointers are easy to deal with –In fact, there is little that can go wrong in Java since pointer access is done for you.
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.
Introduction to C programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 8 - Characters and Strings Outline 8.1Introduction 8.2Fundamentals of Strings and Characters 8.3Character.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
CS 162 Introduction to Computer Science Chapter 17 C++ String Objects Herbert G. Mayer, PSU (Copied from Prof. Phillip Wong at PSU) Status 11/30/2014.
Arrays II (Strings). Data types in C Integer : int i; Double: double x; Float: float y; Character: char ch; char cha[10], chb[]={‘h’,’e’,’l’,’l’,’o’};
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 21 Thanks for Lecture Slides:
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
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.
What is a String? A string is actually a character array.
Chapter 8 Characters and Strings. Objectives In this chapter, you will learn: –To be able to use the functions of the character handling library ( ctype).
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.
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.
CSE 251 Dr. Charles B. Owen Programming in C1 Strings and File I/O.
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.
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.
Principles of Programming - NI Chapter 10: Character & String : In this chapter, you’ll learn about; Fundamentals of Strings and Characters The difference.
Introduction Programs which manipulate character data don’t usually just deal with single characters, but instead with collections of them (e.g. words,
Computer Organization and Design Pointers, Arrays and Strings in C
Strings CSCI 112: Programming in C.
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
INC 161 , CPE 100 Computer Programming
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
ECE Application Programming
Characters and Strings
C Characters and Strings
Fundamentals of Characters and Strings
Lecture 8 String 1. Concept of strings String and pointers
C Programming Tutorial – Part I
CSE 303 Lecture 14 Strings in C
Strings A string is a sequence of characters treated as a group
Computer Science 210 Computer Organization
Arrays in C.
Chapter 8 - Characters and Strings
Computer Science 210 Computer Organization
Object Oriented Programming COP3330 / CGS5409
C Arrays.
Characters and Strings
INC 161 , CPE 100 Computer Programming
Week 9 – Lesson 1 Arrays – Character Strings
Lecture 11 Strings.
C-strings In general, a string is a series of characters treated as a unit. Practically all string implementations treat a string as a variable-length.
CprE 185: Intro to Problem Solving (using C)
EECE.2160 ECE Application Programming
Chapter 16 Pointers and Arrays
Strings What is a string? It is an array of characters terminated with
CPS120: Introduction to Computer Science
EECE.2160 ECE Application Programming
Exercise Arrays.
C++ Programming Lecture 20 Strings
CS31 Discussion 1H Fall18: week 6
C Characters and Strings
EECE.2160 ECE Application Programming
EECE.2160 ECE Application Programming
Introduction to Problem Solving and Programming
Chapter 12: More on C-Strings and the string Class
Presentation transcript:

Strings

CMPE150: Introduction to Computing What is a String? A string is actually a character array. You can use it like a regular array of characters. However, it has also some unique features that make string processing easy. CMPE150: Introduction to Computing

Using Character Arrays Assume you want to read the input until 'Enter' is pressed and convert the input to uppercase. CMPE150: Introduction to Computing

Using Character Arrays #include <stdio.h> int main() { char st[10]; int i=0, j; /* Read characters until 'Enter' is pressed */ do { scanf("%c", &st[i]); if (st[i]=='\n') break; i++; } while (1); /* Convert lowercase to uppercase */ for (j=0; j<i; j++) if (('a'<=st[j]) && (st[j]<='z')) st[j] += 'A'-'a'; /* Print */ printf("%c", st[j]); printf("\n"); return 0; } What is wrong here? CMPE150: Introduction to Computing

CMPE150: Introduction to Computing Using Strings Life is simpler with strings. #include <stdio.h> int main() { char st[10]; int j; /* Read characters until 'Enter' is pressed */ scanf("%s", st); /* Convert lowercase to uppercase */ for (j=0; st[j]!='\0'; j++) if (('a'<=st[j]) && (st[j]<='z')) st[j] += 'A'-'a'; /* Print */ printf("%s\n", st); return 0; } Is this correct? CMPE150: Introduction to Computing

What You Should Keep in Mind Anything written in double quotes (" ") is a string. The end of a string is always marked with the invisible null character '\0'. We say "a string is always null-terminated." All string functions depend on this null character. If you ignore the null character, everything will fail. You have to take into account that null character also consumes one byte. Strings should be treated gently. Failure to abide with the rules results in disaster. CMPE150: Introduction to Computing

CMPE150: Introduction to Computing Strings So, the idea is simple: Obey the following simple rules: When you define the string variable, don't forget to add one byte for the null character. All string functions depend on the null character so don't mess around with the null character. Anything after the null character will be ignored. Anything up to the null character will be considered. CMPE150: Introduction to Computing

CMPE150: Introduction to Computing Strings There are multiple string functions that help programming. (Discussed later.) Learn what type of arguments are required and what they return. Anything in double quotes is a string. You may access a string in double quotes, but cannot change it. (Discussed later.) CMPE150: Introduction to Computing

CMPE150: Introduction to Computing Initializing Strings Instead of initializing the elements of a string one-by-one, you can initialize it using a string. Eg: char st[]="Boğaziçi University"; is equivalent to char st[]={'B','o','ğ','a','z','i','ç','i', ' ','U','n','i','v','e','r','s','i','t','y’, ‘\0’}; CMPE150: Introduction to Computing

CMPE150: Introduction to Computing String Functions You can find several string functions in string.h. strlen(), strcpy(), strcat(), strcmp() CMPE150: Introduction to Computing

CMPE150: Introduction to Computing strlen() int strlen(char *st) Returns the length of its string parameter (excluding null character). Assignment: Implement strlen() yourself. In fact, function prototype is slightly different. I have used these parameter type and return type for the sake of simplicity. CMPE150: Introduction to Computing

CMPE150: Introduction to Computing strlen() Then, we can rewrite the lower-to-uppercase conversion as follows: /* Convert lowercase to uppercase */ for (j=0; j<strlen(st); j++) if (('a'<=st[j]) && (st[j]<='z')) st[j] += 'A'-'a'; Which one is better? CMPE150: Introduction to Computing

CMPE150: Introduction to Computing strcpy() If you want to copy the contents of a string variable to another, simple assignment does not work ! Eg: char st1[5]="abcd", st2[5]="xyz"; st1=st2; is wrong. You have to copy the characters one-by-one. There is a specific function that does this. CMPE150: Introduction to Computing

CMPE150: Introduction to Computing strcpy() char *strcpy(char *dest, char *source) Copies all characters in source into dest. Of course terminates dest with null char. Returns starting address of dest. Assignment: Implement strcpy() yourself. CMPE150: Introduction to Computing

CMPE150: Introduction to Computing strcpy() char st1[6]="abdef", st2[5]="xyz"; strcpy(st1,st2); st1[2]='M'; st2[3]='N'; printf("<st1:%s>\n",st1); printf("<st2:%s>\n",st2); What is the output? CMPE150: Introduction to Computing

CMPE150: Introduction to Computing strcat() If you want to attach two strings, use strcat(). char *strcat(char *dest, char *source) Attaches source to the tail of dest. Chars in dest are not lost. Returns starting address of dest. Assignment: Do it yourself. CMPE150: Introduction to Computing

g_st=strcat("Hello ",name); Write a function that reads a name from the input, prepends it with "Hello ", and updates its parameter to contain this greeting string. (You may assume the caller passes a parameter that is large enough.) void greet(char g_st[]) { char name[20]; scanf("%s", name); strcpy(g_st,"Hello "); strcat(g_st, name); } Why didn't we simply write g_st=strcat("Hello ",name); CMPE150: Introduction to Computing

CMPE150: Introduction to Computing strcmp() You may also check the lexicographical ordering of two strings. int strcmp(char *st1, char *st2) Returns <0 if st1 comes before st2. Returns 0 if st1 is identical to st2. Returns >0 if st1 comes after st2. Assignment: Do it yourself. CMPE150: Introduction to Computing

CMPE150: Introduction to Computing Safe Operation As we discussed before, string functions are not safe in general since the size of the string is not controlled (everything depends on the occurrence of the null character). CMPE150: Introduction to Computing

CMPE150: Introduction to Computing Safe Operation A solution is the use of safer functions: strncpy(), strncat(), strncmp() strncpy(dest,src,n) Copy at most n characters of src to dest. strncat(dest,src,n) Concatenate at most n characters of src to dest. strncmp(dest,src,n) Compare at most n characters of dest. CMPE150: Introduction to Computing

CMPE150: Introduction to Computing Safe Input Using scanf() is dangerous if the user is not careful (or is malicious). Safer (but cumbersome) method: Read input with fgets() into a string. Process the string with sscanf() or snscanf(). CMPE150: Introduction to Computing

CMPE150: Introduction to Computing Safe Input fgets(char *s, int n, FILE *stream) Read at most n-1 characters into s from stream. Eg: char st[50]; fgets(st,sizeof(st),stdin); CMPE150: Introduction to Computing

CMPE150: Introduction to Computing String Processing sscanf() is very similar to scanf(). The only difference is that it takes the input from a string rather than the console. sscanf(char *s, const char *format, ...) Eg: char input_str[50]; int i; float f; char st[10]; fgets(input_str,sizeof(input_str),stdin); sscanf(input_str,"%d %f %s", &i, &f, st); CMPE150: Introduction to Computing