0% found this document useful (0 votes)
18 views8 pages

Strings

Strings

Uploaded by

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

Strings

Strings

Uploaded by

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

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.

How to declare a string?

Here's how you can declare strings:

char s[5];

Here, we have declared a string of 5 characters.

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'};


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.

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 "Ritchie" was stored in the
name string. It's because there was a space after Dennis.

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.

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 the name string.

To print the string, we have used puts(name);.

Note: The gets() function can also be to take input from the user. However, it is removed from
the C standard.

It's because gets() allows you to input any length of characters. Hence, there might be a buffer
overflow.

Passing Strings to Functions

Strings can be passed to a function in a similar way as arrays.

Example 3: Passing string to a Function


#include <stdio.h>
void displayString(char str[]);

int main()
{
char str[50];
printf("Enter string: ");
fgets(str, sizeof(str), stdin);
displayString(str); // Passing string to a function.
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}

Strings and Pointers

Similar like arrays, string names are "decayed" to pointers. Hence, you can use pointers to
manipulate elements of the string. check C Arrays and Pointers before you check this example.

Example 4: Strings and Pointers


#include <stdio.h>

int main(void) {
char name[] = "Harry Potter";

printf("%c", *name); // Output: H


printf("%c", *(name+1)); // Output: a
printf("%c", *(name+7)); // Output: o

char *namePtr;

namePtr = name;
printf("%c", *namePtr); // Output: H
printf("%c", *(namePtr+1)); // Output: a
printf("%c", *(namePtr+7)); // Output: o
}

Commonly Used String Functions

• strlen() - calculates the length of a string


• strcpy() - copies a string to another
• strcmp() - compares two strings
• strcat() - concatenates two strings

String Manipulations In C Programming Using Library Functions


You need to often manipulate strings according to the need of a problem. Most, if not all, of the
time string manipulation can be done manually but, this makes programming complex and large.

To solve this, C supports a large number of string handling functions in the standard library
"string.h".

Few commonly used string handling functions are discussed below:


Function Work of Function

strlen() computes string's length

strcpy() copies a string to another

strcat() concatenates(joins) two strings

strcmp() compares two strings

strlwr() converts string to lowercase

strupr() converts string to uppercase

Strings handling functions are defined under "string.h" header file.

#include <string.h>

Note: You have to include the code below to run string handling functions.

gets() and puts()

Functions gets() and puts() are two string functions to take string input from the user and display
it respectively as mentioned in the previous chapter.

#include<stdio.h>

int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}

Note: Though, gets() and puts() function handle strings, both these functions are defined in
"stdio.h" header file.
String Examples in C Programming
Find the Frequency of a Character
#include <stdio.h>
int main() {
char str[1000], ch;
int count = 0;

printf("Enter a string: ");


fgets(str, sizeof(str), stdin);

printf("Enter a character to find its frequency: ");


scanf("%c", &ch);

for (int i = 0; str[i] != '\0'; ++i) {


if (ch == str[i])
++count;
}

printf("Frequency of %c = %d", ch, count);


return 0;
}

Output

Enter a string: This website is awesome.


Enter a character to find its frequency: e
Frequency of e = 4

In this program, the string entered by the user is stored in str.

Then, the user is asked to enter the character whose frequency is to be found. This is stored in
variable ch.

Then, a for loop is used to iterate over characters of the string. In each iteration, if the character
in the string is equal to the ch, count is increased by 1.

Finally, the frequency stored in the count variable is printed.

Program to count vowels, consonants etc.


#include <stdio.h>
int main() {
char line[150];
int vowels, consonant, digit, space;

vowels = consonant = digit = space = 0;

printf("Enter a line of string: ");


fgets(line, sizeof(line), stdin);

for (int i = 0; line[i] != '\0'; ++i) {


if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' ||
line[i] == 'o' || line[i] == 'u' || line[i] == 'A' ||
line[i] == 'E' || line[i] == 'I' || line[i] == 'O' ||
line[i] == 'U') {
++vowels;
} else if ((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' &&
line[i] <= 'Z')) {
++consonant;
} else if (line[i] >= '0' && line[i] <= '9') {
++digit;
} else if (line[i] == ' ') {
++space;
}
}

printf("Vowels: %d", vowels);


printf("\nConsonants: %d", consonant);
printf("\nDigits: %d", digit);
printf("\nWhite spaces: %d", space);
return 0;
}

Output

Enter a line of string: adfslkj34 34lkj343 34lk


Vowels: 1
Consonants: 11
Digits: 9
White spaces: 2

Here, the string entered by the user is stored in the line variable.

Initially, the variables vowel, consonant, digit, and space are initialized to 0.

Then, a for loop is used to iterate over characters of a string. In each iteration, whether the
character is vowel, consonant, digit, and space is checked. Suppose, the character is a vowel, in
this case, the vowel variable is increased by 1.

When the loop ends, the number of vowels, consonants, digits and white spaces are stored in
variables vowel, consonant, digit and space respectively.

Calculate Length of String without Using strlen() Function


#include <stdio.h>
int main() {
char s[] = "Programming is fun";
int i;

for (i = 0; s[i] != '\0'; ++i);

printf("Length of the string: %d", i);


return 0;
}
Output

Length of the string: 18

Here, using a for loop, we have iterated over characters of the string from i = 0 to until '\0'
(null character) is encountered. In each iteration, the value of i is increased by 1.

When the loop ends, the length of the string will be stored in the i variable.

Remove Characters in String Except Alphabets


#include <stdio.h>
int main() {
char line[150];
printf("Enter a string: ");
gets(line);
for (int i = 0; line[i] != '\0'; ++i) {
while (!((line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' &&
line[i] <= 'Z') || line[i] == '\0')) {
for (int j = i; line[j] != '\0'; ++j) {
line[j] = line[j + 1];
}
line[j] = '\0';
}
}
printf("Output String: ");
puts(line);
return 0;
}

Output

Enter a string: p2'r-o@gram84iz./


Output String: programiz

This program takes a string input from the user and stores in the line variable. Then, a for loop
is used to iterate over characters of the string.

If the character in a string is not an alphabet, it is removed from the string and the position of the
remaining characters are shifted to the left by 1 povariable

You might also like