Professional Documents
Culture Documents
Computer Programming
Strings
Overview
! Introduction
! Usage
! Declaration
! Initialization
! Read from User
! gets() and puts()
! Strings and functions
! Internal string functions
! String as 2D array
Introduction
! Before you can work with strings, you need to declare them first. Since string
is an array of characters. You declare strings in a similar way like you do with
arrays.
! Here's how you declare a string:
! char s[5];
Initialization
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: "); Enter name: Amrita
Your name is Amrita.
scanf("%s", name);
printf("Your name is %s.\n", name);
return 0;
}
gets() and puts()
#include <stdio.h>
Enter name: I am studying at Amrita
int main() Name: I am studying at Amrita
{
char name[30];
printf("Enter name: ");
gets(name); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
Strings as function parameters
#include <stdio.h>
void displayString(char str[]); Enter string: Amrita School of Engineering
int main() String Output: Amrita School of Engineering
{
char str[50];
printf("Enter string: ");
gets(str);
displayString(str); // Passing string to a function.
return 0;
}
! All the internal string functions are included in “string.h” header file.
! It has to be included in your code to use the internal functions.
! strlen(): The function takes a single argument, i.e, the string variable
whose length is to be found, and returns the length of the string passed.
! strcpy() : Function copies the string to another character array.
! strcmp(): The strcmp() function compares two strings and returns 0 if
both strings are identical.
! strcat(): concatenates (joins) two strings.
Internal string functions