SPL Lec 8 (String) - 1
SPL Lec 8 (String) - 1
The string can be defined as the one-dimensional array of characters terminated by a null ('\0').
Each character in the array occupies one byte of memory, and the last character must always
be 0. The termination character ('\0') is important in a string since it is the only way to identify
where the string ends.
There are two ways to declare a string in c language.
1. By char array
2. By string literal
Let's see the example of declaring string by char array in C language.
char ch[10]={‘s, 'a', ‘b', ‘b', ‘i', ‘r', ‘h', ‘o', ‘s', ‘s', '\0'};
Array Vs String
Example
#include<stdio.h>
#include <string.h>
int main(){
char ch[11]={‘S', 'a', ‘k', ‘i', ‘l','\0'};
char ch2[11]=“Sakil";
printf("Char Array Value is: %s\n", ch);
printf("String Literal Value is: %s\n", ch2);
return 0;
}
Reading a line of text
Example
#include<stdio.h>
#include <string.h>
int main(){
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}
String pointer
It is not possible to read, with scanf(), a string with a string pointer. You have to use
a character array and a pointer. See this example:
String Function
Example of String using Function To Compare String
#include<stdio.h>
#include <string.h>
int main(){
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
Example of String using Function To Find String Length
#include<stdio.h>
#include <string.h>
int main(){
char ch[20]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
printf("Length of string is: %d",strlen(ch));
return 0;
}
Example of String using Function To Reverse String
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s",str);
printf("\nReverse String is: %s",strrev(str));
return 0;
}
Math Function
Example of math functions found in math.h header file
#include<stdio.h>
#include <math.h>
int main(){
printf("\n%f",ceil(3.6));
printf("\n%f",ceil(3.3));
printf("\n%f",floor(3.6));
printf("\n%f",floor(3.2));
printf("\n%f",sqrt(16));
printf("\n%f",sqrt(7));
printf("\n%f",pow(2,4));
printf("\n%f",pow(3,3));
printf("\n%d",abs(-12));
return 0;
}
Lab Task:
Write a C program to Copy String Manually