SlideShare a Scribd company logo
C Programming Strings
In C programming, a string is a sequence of characters terminated with a
null character 0. For example:
char c[] = "c string";
When the compiler encounters a sequence of characters enclosed in the
double quotation marks, it appends a null character 0 at the end by
default.
Memory Diagram
How to declare a string?
Here's how you can declare strings:
char s[5];
String Declaration in C
How to initialize strings?
You can initialize strings in a number of ways.
char c[] = "abcd";
char c[50] = "abcd";
char c[] = {'a', 'b', 'c', 'd', '0'};
char c[5] = {'a', 'b', 'c', 'd', '0'};
String Initialization in C
Let's take another example:
char c[5] = "abcde";
Here, we are trying to assign 6 characters (the last character is '0') to
a char array having 5 characters. This is bad and you should never do this.
Assigning Values to Strings
Arrays and strings are second-class citizens in C; they do not support the
assignment operator once it is declared. For example,
char c[100];
c = "C programming"; // Error! array type is not assignable.
Note: Use the strcpy() function to copy the string instead.
Read String from the user
You can use the scanf() function to read a string.
The scanf() function reads the sequence of characters until it
encounters whitespace (space, newline, tab, etc.).
Example 1: scanf() to read a string
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Output
Enter name: Dennis Ritchie
Your name is Dennis.
Even though Dennis Ritchie was entered in the above program,
only "Dennis" was stored in the name string. It's because there was a space
after Dennis.
Also notice that we have used the code name instead of &name with scanf().
scanf("%s", name);
This is because name is a char array, and we know that array names decay
to pointers in C.
Thus, the name in scanf() already points to the address of the first element in
the string, which is why we don't need to use &.
How to read a line of text?
You can use the fgets() function to read a line of string. And, you can
use puts() to display the string.
Example 2: fgets() and puts()
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
Output
Enter name: Tom Hanks
Name: Tom Hanks
Here, we have used fgets() function to read a string from the user.
Standard C Library – String.h Functions
The C language comes bundled with <string.h> which contains some useful
string-handling functions. Some of them are as follows:
Function Name Description
strlen(string_name) Returns the length of string name.
strcpy(s1, s2) Copies the contents of string s2 to string s1.
strcmp(str1, str2)
Compares the first string with the second string. If strings are the
same it returns 0.
strcat(s1, s2)
Concat s1 string with s2 string and the result is stored in the first
string.
strlwr() Converts string to lowercase.
strupr() Converts string to uppercase.
Function Name Description
strstr(s1, s2) Find the first occurrence of s2 in s1.
Example of String By Using Above-mentioned Functions:
#include <stdio.h>
#include <string.h>
int main () {
char str1[12] = “John”;
char str2[12] = “Potter”;
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf(“strcpy( str3, str1) : %sn”, str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf(“strcat( str1, str2): %sn”, str1 );
/* total length of str1 after concatenation */
len = strlen(str1);
printf(“strlen(str1) : %dn”, len );
return 0;
}
Output:
strcpy( str3, str1) : John
strcat( str1, str2): JohnPotter
strlen(str1) : 10
Traverse String
There are two ways to traverse a string
 By using the length of string
 By using the null character.
 Example of using the length of string
#include<stdio.h>
void main ()
{
char s[11] = “byjuslearning”;
int i = 0;
int count = 0;
while(i<11)
{
if(s[i]==’a’ || s[i] == ‘e’ || s[i] == ‘i’ || s[i] == ‘u’ || s[i] == ‘o’)
{
count ++;
}
i++;
}
printf(“The number of vowels %d”,count);
}
Output: The number of vowels : 3
 Second Example: Using Null Character
#include<stdio.h>
void main ()
{
char s[11] = “byjuslearning”;
int i = 0;
int count = 0;
while(s[i] != NULL)
{
if(s[i]==’a’ || s[i] == ‘e’ || s[i] == ‘i’ || s[i] == ‘u’ || s[i] == ‘o’)
{
count ++;
}
i++;
}
printf(“The number of vowels %d”,count);
}
Output: The number of vowels: 3

More Related Content

Similar to C Programming Strings.docx

Similar to C Programming Strings.docx (20)

introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programming
 
Unit 2
Unit 2Unit 2
Unit 2
 
Strings
StringsStrings
Strings
 
Lesson in Strings for C Programming Lessons
Lesson in Strings for C Programming LessonsLesson in Strings for C Programming Lessons
Lesson in Strings for C Programming Lessons
 
Strings IN C
Strings IN CStrings IN C
Strings IN C
 
String in programming language in c or c++
String in programming language in c or c++String in programming language in c or c++
String in programming language in c or c++
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 
Module-2_Strings concepts in c programming
Module-2_Strings concepts in c programmingModule-2_Strings concepts in c programming
Module-2_Strings concepts in c programming
 
Arrays
ArraysArrays
Arrays
 
c programming
c programmingc programming
c programming
 
Data structure week 3
Data structure week 3Data structure week 3
Data structure week 3
 
Lecture 2. mte 407
Lecture 2. mte 407Lecture 2. mte 407
Lecture 2. mte 407
 
STRING FUNCTION - Programming in C.pptx
STRING FUNCTION -  Programming in C.pptxSTRING FUNCTION -  Programming in C.pptx
STRING FUNCTION - Programming in C.pptx
 
pps unit 3.pptx
pps unit 3.pptxpps unit 3.pptx
pps unit 3.pptx
 
Array &strings
Array &stringsArray &strings
Array &strings
 
String_C.pptx
String_C.pptxString_C.pptx
String_C.pptx
 
Team 1
Team 1Team 1
Team 1
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptx
 
string , pointer
string , pointerstring , pointer
string , pointer
 
Strings part2
Strings part2Strings part2
Strings part2
 

More from 8759000398

More from 8759000398 (9)

COMPUTER WINDOWS AND ITS LAB ASSESSMENT.docx
COMPUTER WINDOWS AND ITS LAB ASSESSMENT.docxCOMPUTER WINDOWS AND ITS LAB ASSESSMENT.docx
COMPUTER WINDOWS AND ITS LAB ASSESSMENT.docx
 
Testing in Software Engineering.docx
Testing in Software Engineering.docxTesting in Software Engineering.docx
Testing in Software Engineering.docx
 
SAD_UnitII.docx
SAD_UnitII.docxSAD_UnitII.docx
SAD_UnitII.docx
 
JavaScript Date Objects.docx
JavaScript Date Objects.docxJavaScript Date Objects.docx
JavaScript Date Objects.docx
 
Nursing Infromatics.pptx
Nursing Infromatics.pptxNursing Infromatics.pptx
Nursing Infromatics.pptx
 
Basics of C.ppt
Basics of C.pptBasics of C.ppt
Basics of C.ppt
 
newone2.pdf
newone2.pdfnewone2.pdf
newone2.pdf
 
College app for android device
College app for android deviceCollege app for android device
College app for android device
 
Android
AndroidAndroid
Android
 

Recently uploaded

678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Accounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdfAccounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdf
YibeltalNibretu
 

Recently uploaded (20)

UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdfDanh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
 
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfINU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
NCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdfNCERT Solutions Power Sharing Class 10 Notes pdf
NCERT Solutions Power Sharing Class 10 Notes pdf
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
B.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdfB.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdf
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Accounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdfAccounting and finance exit exam 2016 E.C.pdf
Accounting and finance exit exam 2016 E.C.pdf
 

C Programming Strings.docx

  • 1. C Programming Strings In C programming, a string is a sequence of characters terminated with a null character 0. For example: char c[] = "c string"; When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character 0 at the end by default. Memory Diagram How to declare a string? Here's how you can declare strings: char s[5]; String Declaration in C How to initialize strings? You can initialize strings in a number of ways. char c[] = "abcd"; char c[50] = "abcd"; char c[] = {'a', 'b', 'c', 'd', '0'};
  • 2. char c[5] = {'a', 'b', 'c', 'd', '0'}; String Initialization in C Let's take another example: char c[5] = "abcde"; Here, we are trying to assign 6 characters (the last character is '0') to a char array having 5 characters. This is bad and you should never do this. Assigning Values to Strings Arrays and strings are second-class citizens in C; they do not support the assignment operator once it is declared. For example, char c[100]; c = "C programming"; // Error! array type is not assignable. Note: Use the strcpy() function to copy the string instead. Read String from the user You can use the scanf() function to read a string. The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab, etc.). Example 1: scanf() to read a string #include <stdio.h> int main()
  • 3. { char name[20]; printf("Enter name: "); scanf("%s", name); printf("Your name is %s.", name); return 0; } Output Enter name: Dennis Ritchie Your name is Dennis. Even though Dennis Ritchie was entered in the above program, only "Dennis" was stored in the name string. It's because there was a space after Dennis. Also notice that we have used the code name instead of &name with scanf(). scanf("%s", name); This is because name is a char array, and we know that array names decay to pointers in C. Thus, the name in scanf() already points to the address of the first element in the string, which is why we don't need to use &. How to read a line of text? You can use the fgets() function to read a line of string. And, you can use puts() to display the string. Example 2: fgets() and puts() #include <stdio.h> int main() { char name[30];
  • 4. printf("Enter name: "); fgets(name, sizeof(name), stdin); // read string printf("Name: "); puts(name); // display string return 0; } Output Enter name: Tom Hanks Name: Tom Hanks Here, we have used fgets() function to read a string from the user. Standard C Library – String.h Functions The C language comes bundled with <string.h> which contains some useful string-handling functions. Some of them are as follows: Function Name Description strlen(string_name) Returns the length of string name. strcpy(s1, s2) Copies the contents of string s2 to string s1. strcmp(str1, str2) Compares the first string with the second string. If strings are the same it returns 0. strcat(s1, s2) Concat s1 string with s2 string and the result is stored in the first string. strlwr() Converts string to lowercase. strupr() Converts string to uppercase.
  • 5. Function Name Description strstr(s1, s2) Find the first occurrence of s2 in s1. Example of String By Using Above-mentioned Functions: #include <stdio.h> #include <string.h> int main () { char str1[12] = “John”; char str2[12] = “Potter”; char str3[12]; int len ; /* copy str1 into str3 */ strcpy(str3, str1); printf(“strcpy( str3, str1) : %sn”, str3 ); /* concatenates str1 and str2 */ strcat( str1, str2); printf(“strcat( str1, str2): %sn”, str1 ); /* total length of str1 after concatenation */ len = strlen(str1); printf(“strlen(str1) : %dn”, len ); return 0; }
  • 6. Output: strcpy( str3, str1) : John strcat( str1, str2): JohnPotter strlen(str1) : 10 Traverse String There are two ways to traverse a string  By using the length of string  By using the null character.  Example of using the length of string #include<stdio.h> void main () { char s[11] = “byjuslearning”; int i = 0; int count = 0; while(i<11) { if(s[i]==’a’ || s[i] == ‘e’ || s[i] == ‘i’ || s[i] == ‘u’ || s[i] == ‘o’) { count ++; } i++; } printf(“The number of vowels %d”,count);
  • 7. } Output: The number of vowels : 3  Second Example: Using Null Character #include<stdio.h> void main () { char s[11] = “byjuslearning”; int i = 0; int count = 0; while(s[i] != NULL) { if(s[i]==’a’ || s[i] == ‘e’ || s[i] == ‘i’ || s[i] == ‘u’ || s[i] == ‘o’) { count ++; } i++; } printf(“The number of vowels %d”,count); } Output: The number of vowels: 3