0% found this document useful (0 votes)
83 views11 pages

How To Declare A String?: Strings

In C programming, a string is an array of characters terminated with a null character. Strings can be declared and initialized in several ways such as a character array initialized with string values or characters. Common string functions like strlen, strcpy, strcmp etc are used to work with strings. Functions are used to read strings from user, display strings, concatenate and compare strings. Parameters are passed by reference to functions using character array name.

Uploaded by

gshreya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views11 pages

How To Declare A String?: Strings

In C programming, a string is an array of characters terminated with a null character. Strings can be declared and initialized in several ways such as a character array initialized with string values or characters. Common string functions like strlen, strcpy, strcmp etc are used to work with strings. Functions are used to read strings from user, display strings, concatenate and compare strings. Parameters are passed by reference to functions using character array name.

Uploaded by

gshreya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Strings: In C programming, a string is a sequence of characters terminated with a null

character \0. For example:

int 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.

How to declare a string?


Here's how you can declare strings:

1. char s[5];

initialize strings in a number of ways.

1. char c[] = "abcd";


2.
3. char c[50] = "abcd";
4.
5. char c[] = {'a', 'b', 'c', 'd', '\0'};
6.
7. char c[5] = {'a', 'b', 'c', 'd', '\0'};

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.).

1. #include <stdio.h>
2. int main()
3. {
4. char name[20];
5. printf("Enter name: ");
6. scanf("%s", name);
7. printf("Your name is %s.", name);
8. return 0;
9. }

use the fgets() function to read a line of string. And, you can use puts() to display the string.

1. #include <stdio.h>
2. int main()
3. {
4. char name[30];
5. printf("Enter name: ");
6. fgets(name, sizeof(name), stdin); // read string
7. printf("Name: ");
8. puts(name); // display string
9. return 0;
10. }

Here, we have used fgets() function to read a string from the user.


fgets(name, sizeof(name), stdlin); // read string
The sizeof(name) results to 30. Hence, we can take a maximum of 30 characters as input which
is the size of name string.
To print the string, we have used puts(name);.

Predefined functions:

1. #include <stdio.h>
2. #include <string.h>
3. int main()
4. {
5. char a[20]="Program";
6. char b[20]={'P','r','o','g','r','a','m','\0'};
7. char c[20];
8.
9. printf("Enter string: ");
10. gets(c);
11.
12. printf("Length of string a = %d \n",strlen(a));
13.
14. //calculates the length of string before null charcter.
15. printf("Length of string b = %d \n",strlen(b));
16. printf("Length of string c = %d \n",strlen(c));
17.
18. return 0;
19. }

The strlen() function is defined in <string.h> header file.

The strcpy() function copies the string pointed by source (including the null character) to the
character array destination.
This function returns character array destination.

1. #include <stdio.h>
2. #include <string.h>
3.
4. int main()
5. {
6. char str1[10]= "awesome";
7. char str2[10];
8. char str3[10];
9.
10. strcpy(str2, str1);
11. strcpy(str3, "well");
12. puts(str2);
13. puts(str3);
14.
15. return 0;
16. }

char* strcpy(char* destination, const char* source);

C strcmp() Prototype
int strcmp (const char* str1, const char* str2);

The strcmp() compares two strings character by character. If the first character of two strings
are equal, next character of two strings are compared. This continues until the corresponding
characters of two strings are different or a null character '\0' is reached.

Return Value Remarks

0 if both strings are identical (equal)

negative if the ASCII value of first unmatched character is less than second.

positive
integer if the ASCII value of first unmatched character is greater than second.

1. #include <stdio.h>
2. #include <string.h>
3.
4. int main()
5. {
6. char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
7. int result;
8.
9. // comparing strings str1 and str2
10. result = strcmp(str1, str2);
11. printf("strcmp(str1, str2) = %d\n", result);
12.
13. // comparing strings str1 and str3
14. result = strcmp(str1, str3);
15. printf("strcmp(str1, str3) = %d\n", result);
16.
17. return 0;
18. }
_________________

C strcat() Prototype
char *strcat(char *dest, const char *src)

It takes two arguments, i.e, two strings or character arrays, and stores the resultant
concatenated string in the first string specified in the argument.

1. #include <stdio.h>
2. #include <string.h>
3. int main()
4. {
5. char str1[] = "This is ", str2[] = "C pro";
6.
7. //concatenates str1 and str2 and resultant string is stored in str1.
8. strcat(str1,str2);
9.
10. puts(str1);
11. puts(str2);
12.
13. return 0;
14. }
15. #include <stdio.h>
16. #include <string.h>
17. int main()
18. {
19. /* String Declaration*/
20. char nickname[20];
21.
22. printf("Enter your Nick name:");
23.
24. /* I am reading the input string and storing it in nickname
25. * Array name alone works as a base address of array so
26. * we can use nickname instead of &nickname here
27. */
28. scanf("%s", nickname);
29.
30. /*Displaying String*/
31. printf("%s",nickname);
32.
33. return 0;
34. }
35. ______________________
36.
37. #include <stdio.h>
38. #include <string.h>
39. int main()
40. {
41. /* String Declaration*/
42. char nickname[20];
43.
44. /* Console display using puts */
45. puts("Enter your Nick name:");
46.
47. /*Input using gets*/
48. gets(nickname);
49.
50. puts(nickname);
51.
52. return 0;
53. }
Q1. C Program to Find the Frequency of Characters in a String
1. int main()
2. {
3. char str[1000], ch;
4. int i, frequency = 0;
5.
6. printf("Enter a string: ");
7. gets(str);
8.
9. printf("Enter a character to find the frequency: ");
10. scanf("%c",&ch);
11.
12. for(i = 0; str[i] != '\0'; ++i)
13. {
14. if(ch == str[i])
15. ++frequency;
16. }
17.
18. printf("Frequency of %c = %d", ch, frequency);
19.
20. return 0;
21. }
Q2. Program to count vowels, consonants
1. int main()
2. {
3. char line[150];
4. int i, vowels, consonants, digits, spaces;
5.
6. vowels = consonants = digits = spaces = 0;
7.
8. printf("Enter a line of string: ");
9. scanf("%[^\n]", line);
10.
11. for(i=0; line[i]!='\0'; ++i)
12. {
13. if(line[i]=='a' || line[i]=='e' || line[i]=='i' ||
14. line[i]=='o' || line[i]=='u' || line[i]=='A' ||
15. line[i]=='E' || line[i]=='I' || line[i]=='O' ||
16. line[i]=='U')
17. {
18. ++vowels;
19. }
20. else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
21. {
22. ++consonants;
23. }
24. else if(line[i]>='0' && line[i]<='9')
25. {
26. ++digits;
27. }
28. else if (line[i]==' ')
29. {
30. ++spaces;
31. }
32. }
33.
34. printf("Vowels: %d",vowels);
35. printf("\nConsonants: %d",consonants);
36. printf("\nDigits: %d",digits);
37. printf("\nWhite spaces: %d", spaces);
38.
39. return 0;
40. }

Q3 Reverse a sentence using recursion


1. #include <stdio.h>
2. void reverseSentence();
3.
4. int main()
5. {
6. printf("Enter a sentence: ");
7. reverseSentence();
8.
9. return 0;
10. }
11.
12. void reverseSentence()
13. {
14. char c;
15. scanf("%c", &c);
16.
17. if( c != '\n')
18. {
19. reverseSentence();
20. printf("%c",c);
21. }
22. }
To Practice:

C Program to Find the Length of a String

C program to Concatenate Two Strings

C Program to Copy a String

C Program to Remove all Characters in a String except alphabet

C Program to Sort Elements in Lexicographical Order (Dictionary


Order)

How to pass and use strings in functions in C programming language.

We know that a string is a sequence of characters enclosed in double quotes.


For example, "Hello World" is a string and it consists of a sequence of English letters in both
uppercase and lowercase and the two words are separated by a white space. So, there are total
11 characters.
We know that a string in C programming language ends with a NULL \0 character. So, in order
to save the above string we will need an array of size 12. The first 11 places will be used to
store the words and the space and the 12th place will be used to hold the NULL character to
mark the end.

Function declaration to accept one dimensional string


We know that strings are saved in arrays so, to pass an one dimensional array to a function we
will have the following declaration.

returnType functionName(char str[]);

Example:

void displayString(char str[]);

In the above example we have a function by the name displayString and it takes an argument


of type char and the argument is an one dimensional array as we are using the [] square
brackets.

Passing one dimensional string to a function


To pass a one dimensional string to a function as an argument we just write
the name of the string array variable.
In the following example we have a string array variable message and it is
passed to the displayString function.

#include <stdio.h>

void displayString(char []);

int main(void) {

// variables

char

message[] = "Hello World";

// print the string message

displayString(message);

return 0;

void displayString(char str[]) {

printf("String: %s\n", str);

Another Way:

#include <stdio.h>

void displayString(char []);

int main(void) {

// variables
char

message[] = "Hello World";

// print the string message

displayString(message);

return 0;

void displayString(char str[]) {

int i = 0;

printf("String: ");

while (str[i] != '\0') {

printf("%c", str[i]);

i++;

printf("\n");

Function declaration to accept two dimensional


string
In order to accept two dimensional string array the function declaration will
look like the following.

returnType functionName(char [][C], type rows);

Example:
void displayCities(char str[][50], int rows);

In the above example we have a function by the name displayCities and it takes a two


dimensional string array of type char.
The str is a two dimensional array as because we are using two [][] sqaure brackets.
It is important to specify the second dimension of the array and in this example the second
dimension i.e., total number of columns is 50.
The second parameter rows tell us about the total number of rows in the give two dimensional
string array str.
The return type for this function is set to void that means it will return no value.

#include <stdio.h>

void displayCities(char [][50], int rows);

int main(void) {

// variables

char

cities[][50] = {

"Bangalore",

"Chennai",

"Kolkata",

"Mumbai",

"New Delhi"

};

int rows = 5;

// print the name of the cities

displayCities(cities, rows);
return 0;

void displayCities(char str[][50], int rows) {

// variables

int r, i;

printf("Cities:\n");

for (r = 0; r < rows; r++) {

i = 0;

while(str[r][i] != '\0') {

printf("%c", str[r][i]);

i++;

printf("\n");

You might also like