Strings in C Array of characters is called a string.

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.
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.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
C programming---String. String Literals A string literal is a sequence of characters enclosed within double quotes: “hello world”
1 Introduction to Computing Lecture 11 Character Strings Assist.Prof.Dr. Nükhet ÖZBEK Ege University Department of Electrical&Electronics Engineering
1 Strings ( מחרוזות ). 2 Agenda Definition and initialization Termination Input / Output String library.
CS 192 Lecture 11 Winter 2003 December 29-30, 2003 Dr. Shafay Shamail.
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 7 Strings. An array of characters Used to store text Another way to initialize: char A[ ]=“blabla”;
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.
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
CNG 140 C Programming (Lecture set 9) Spring Chapter 9 Character Strings.
Chapter 8: Character and String CMPD144: Programming 1.
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:
Strings program. C Program to Check if a given String is Palindrome #include void main() { char string[25], reverse_string[25] = {'\0'}; int i, length.
Strings program. C Program to Check if a given String is Palindrome #include void main() { char string[25], reverse_string[25] = {'\0'}; int i, length.
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.
String Array (Multidimensional Arrays) 1. A string array is a multidimensional array of strings. It is declared in the following syntax: char variable_name[No_of_strings][size_of_each_string];
Strings, Pointers and Tools
Principles of Programming Chapter 8: Character & String  In this chapter, you’ll learn about;  Fundamentals of Strings and Characters  The difference.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
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.
MULTI-DIMENSION ARRAY STRING Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
1 Chapter 8 – Character Arrays and Strings Outline 8.1Introduction 8.2Declaring and Initializing String 8.3Input/output of strings 8.4String-handling Functions.
Chapter 8 “Character Arrays and Strings” Prepared by: Prof. Ajay M. Patel CE, IDS, NU.
Strings CSCI 112: Programming in C.
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
Strings (Continued) Chapter 13
Lecture 8 String 1. Concept of strings String and pointers
Quiz 11/15/16 – C functions, arrays and strings
A First Book of ANSI C Fourth Edition
CSE 303 Lecture 14 Strings in C
Module 2 Arrays and strings – example programs.
Strings A string is a sequence of characters treated as a group
Arrays in C.
מחרוזות קרן כליף.
CS111 Computer Programming
Lecture 8b: Strings BJ Furman 15OCT2012.
C Stuff CS 2308.
CSI 121 Structured Programming Language Lecture 21 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.
Strings.
EECE.2160 ECE Application Programming
Strings What is a string? It is an array of characters terminated with
Chapter 8 Character Arrays and Strings
C Strings Prabhat Kumar Padhy
Example: ? str1 str2 _ void salin(char sasaran[], char sumber[]);
EECE.2160 ECE Application Programming
Exercise Arrays.
Strings Adapted from Dr. Mary Eberlein, UT Austin.
Character Arrays char string1[] = “first”;
Strings #include <stdio.h>
Library in c++ ( as cmath , iostream , …… etc.)
Strings Adapted from Dr. Mary Eberlein, UT Austin.
EECE.2160 ECE Application Programming
Introduction to Problem Solving and Programming
Presentation transcript:

Strings in C Array of characters is called a string. A string is terminated by a null character \0. Ex: “C String” Here “C string” is a string. When compiler encounters a string, it appends \0(null character) at the end of the string. C S t r i n g \0

Declaration of strings Strings are declared in a similar manner as arrays. Only difference is that, strings are of char data type. char s[5];

Initialization of strings In C, string can be initialized in a number of different ways. For convenience and ease, both initialization and declaration are done in the same step. char c[] = "abcd"; OR, char c[50] = "abcd"; char c[] = {'a', 'b', 'c', 'd', '\0'}; char c[5] = {'a', 'b', 'c', 'd', '\0'}; a b c d \0

Reading Strings from user Use scanf() to read a string like any other data type. The scanf() function only takes the first entered word. The function terminates when it encounters a space. Reading words from the user char c[20]; scanf(“%s”,c);

Using scanf() to read a string C program to illustrate how to read string from terminal. Sample output: Enter name: Mani Ratnam Your name is Mani void main() { char name[20]; printf("Enter name: "); scanf("%s",name); printf("Your name is %s",name); }

Using getchar() to read a line of text C program to read a line of text characters. Sample output: Enter name: Mani Ratnam Your name : Mani Ratnam void main() { char name[30], ch; int i=0; printf("Enter name: "); while(ch!=‘\n’) ch=getchar(); name[i]= ch; i++; } name[i]=‘\0’; printf("Your name : %s",name); Using the function getchar(), ch gets a single character from the user each time. This process is repeated until the user enters return (enter key). Finally, the null character is inserted at the end to make it a string.

Using gets() and puts()to read a line of text C program to read a line of text characters. Sample output: Enter name: Mani Ratnam Your name : Mani Ratnam void main() { char name[30]; printf("Enter name: "); gets(name); printf(“Your name: "); puts(name); } Using the function gets(), a series of characters are received until user press enter. The compiler insert the null character at the end to make it a string.

Passing string to a function #include <stdio.h> void displayString(char str[]); void main() { char str[50]; printf("Enter string: "); gets(str); displayString(str); // Passing string c to function. } void displayString(char str[]) printf("String Output: "); puts(str); Strings are just char arrays. So, they can be passed to a function in a similar manner as arrays.

String Handling Functions There are various string operations you can perform manually like: finding the length of a string, concatenating (joining) two strings etc. But, for programmer's ease, many of these library functions are already defined under the header file <string.h>

String Handling Functions String Length Function

strlen(string) #include <stdio.h> #include <string.h> It returns the length of the string without including end character (terminating char ‘\0’). #include <stdio.h> #include <string.h> void main() { char str1[20] = "Book"; printf("Length of string str1: %d", strlen(str1)); }

Length of the string without using built in function #include <stdio.h> void main() { char string[50]; int i, length = 0;   printf("Enter a string \n"); gets(string); /* keep going through each character of the string till its end */ for (i = 0; string[i] != '\0'; i++) length++; } printf(“The length of %s = %d\n", string, length);

strlen vs sizeof strlen returns you the length of the string stored in array, sizeof returns the total allocated size assigned to the array.

strnlen(string , maxlength) It returns length of the string if it is less than the value specified for maxlen (maximum length) otherwise it returns maxlen value. #include <stdio.h> #include <string.h> void main() { char str1[20] = “Record Book"; printf("Length of string str1 when maxlen is 30: %d", strnlen(str1, 30)); printf("Length of string str1 when maxlen is 10: %d", strnlen(str1, 10)); } Output: Length of string str1 when maxlen is 30: 11 Length of string str1 when maxlen is 10: 10

String Handling Functions String Comparing Function

strcmp(string1, string2) If string1 < string2 OR string1 is a substring of string2 then it would result in a negative value. If string1 > string2 then it would return positive value. If string1 == string2 then you would get 0(zero) when you use this function for compare strings.

#include <stdio.h> #include <string.h> void main() { char s1[20] = “Record"; char s2[20] = “Record Book"; if (strcmp(s1,s2)==0) printf("string 1 and string 2 are equal"); } else printf("string 1 and 2 are different");

/*Program to compare Strings without using built in function */  void main() {    char str1[30], str2[30];    int i;     printf("\nEnter two strings :");    gets(str1);    gets(str2);     i = 0;    while (str1[i] == str2[i] && str1[i] != '\0')      {  i++; }    if (str1[i] > str2[i])       printf("str1 > str2");    else if (str1[i] < str2[i])       printf("str1 < str2");    else       printf("str1 = str2");   } /*Program to compare Strings without using built in function */

strncmp(string1, string2, n) It compares both the string till n characters or in other words it compares first n characters of both the strings. void main() { char s1[20] = “Record Book"; char s2[20] = “Record work"; /* below it is comparing first 6 characters of s1 and s2*/ if (strncmp(s1, s2, 6) ==0) { printf("string 1 and string 2 are equal"); else printf("string 1 and 2 are different"); } Output: string1 and string 2 are equal

String Handling Functions String Concatenation Function

strcat(string1, string2) It concatenates two strings and returns the concatenated string. That is, it attaches the string 2 to the RHS of the string 1. int main() { char s1[10] = "Hello"; char s2[10] = "World"; strcat(s1,s2); printf("string after concatenation: %s", s1); return 0; } Output : string after concatenation: HelloWorld

/*Program to concatenate Strings without using built in function */ void main(void) { char str1[25],str2[25]; int i=0, j=0; printf("\nEnter First String:"); gets(str1); printf("\nEnter Second String:"); gets(str2); while(str1[i]!='\0') i++; while(str2[j]!='\0') { str1[i]=str2[j]; j++; } str1[i]='\0'; printf("\nConcatenated String is %s",str1); /*Program to concatenate Strings without using built in function */

strncat(string1, string2, n) It concatenates n characters of str2 to string str1. A terminator char (‘\0’) will always be appended at the end of the concatenated string. int main() { char s1[10] = "Hello"; char s2[10] = “1234"; strncat(s1,s2, 3); printf("Concatenation using strncat: %s", s1); return 0; } Output: Concatenation using strncat: Hello123

String Handling Functions String Copy Function

strcpy(string1, string2) It copies the string str2 into string str1, including the end character (terminator char ‘\0’). void main() { char s1[30] = “hi"; char s2[30] = “programmer"; /* this function has copied s2 into s1*/ strcpy(s1,s2); printf("String s1 is: %s", s1); } Output: String s1 is: programmer

/*Program to copy Strings without using built in function */ void main() { char s1[100], s2[100], i; printf("Enter string s1: "); scanf("%s",s1); for(i = 0; s1[i] != '\0'; ++i) s2[i] = s1[i]; } s2[i] = '\0'; printf("String s2: %s", s2); /*Program to copy Strings without using built in function */

strncpy(string1, string2, n) Case1: If length of str2 > n then it just copies first n characters of str2 into str1. Case2: If length of str2 < n then it copies all the characters of str2 into str1 and appends several terminator chars(‘\0’) to accumulate the length of str1 to make it n. void main() { char first[30] = “hello”; char second[30] =“Amrita”; /* this function has copied first 10 chars of s2 into s1*/ strncpy(s1,s2, 5); printf("String s1 is: %s", s1); } Output: String s1 is:Amrit