Strings in C

Strings in C

Definition

  • A string in C is an array of characters terminated by a special character \0 (null character).

  • Difference between character array and string:

    • A string must end with \0, which marks the end of the string.

  • Strings are used to manipulate text such as words or sentences.

  • Each character occupies one byte of memory.

  • The termination character \0 is important because it tells where the string ends.


Declaration of Strings

Declaring a string is similar to declaring a one-dimensional array.

Syntax

char str_name[size];
  • str_name → name of the string

  • size → maximum number of characters the string can store

  • Remember: one extra space is needed for \0


Initializing a String

char str[] = "mec"; char str[50] = "mec"; char str[] = {'m','e','c','\0'}; char str[4] = {'m','e','c','\0'};

String Input and Output

Using scanf and printf

  • %s format specifier is used.

  • scanf("%s", str) reads only up to the first space.

scanf("%s", str); printf("%s", str);

Example:

Input: mec thrikakkara Output: mec

Reading Full Line Strings

gets() (Deprecated – Unsafe)

  • Reads a full line including spaces.

  • Dangerous because no bounds checking → may cause buffer overflow.

gets(s);

Safer Alternatives

  • fgets(str, size, stdin) ✅ recommended

  • scanf("%[^\n]", str)

  • getline() (in some environments)

fgets(str, 10, stdin);

Reading a Single Character

char ch = getchar();

Printing Strings

  • printf("%s", str)

  • puts(str) → prints string + newline automatically

  • fputs(str, stdout) → prints without adding newline

puts(str); fputs(str, stdout);

gets() vs fgets()

FunctionDescription
gets()        Reads until newline, no size limit → unsafe
fgets()        Reads up to specified size → safe

String Handling Library (string.h)

Include:

#include <string.h>

Common String Functions

FunctionPurpose
strcat()        Concatenate two strings
strchr()        Locate character in string
strcmp()        Compare two strings
strcpy()        Copy string
strlen()        Get string length
strncat()        Concatenate part of string
strncmp()        Compare part of strings
strncpy()        Copy part of string
strrchr()        Find last occurrence of character
strstr()        Find substring
strlwr()        Convert to lowercase*
strupr()        Convert to uppercase*
strrev()        Reverse string*

*Not available in standard GCC (Turbo C only / non-standard).


Important String Functions

1. strlen() – String Length

  • Returns length excluding \0

printf("%lu", strlen(s));

2. strcpy() – Copy String

strcpy(destination, source);

3. strcat() – Concatenate Strings

strcat(s1, s2);

4. strcmp() – Compare Strings

  • Returns 0 if equal

if(strcmp(str1,str2)==0) printf("Strings are equal");

5. strrev() – Reverse String (non-standard)

strrev(str);

Important Notes

  • Functions like strrev(), strlwr(), strupr() are not part of standard C and may not work with GCC.

  • C does not provide operators for:

    • string assignment

    • concatenation

    • comparison

  • Strings in C are simply arrays of characters.


Sample Programs

 
C program to read and print a string

#include<stdio.h>
int main()
{  
    // declaring string
char str[50];
    // reading string
scanf("%s",str);
    // print string
printf("%s",str);
return 0;
}
 
read a string and print the characters  backwards
#include<stdio.h>
#include<string.h>
int main() {

char S[100];
int l, i;
printf("Enter the string..\n");
gets(S);
  l = strlen(S);

printf("\nbackward\n");
for (i = l-1; i >= 0; --i)
printf(" %c",S[i]);
}
 
Find the length of a string without using built in functions(university question).
 #include<stdio.h>
int main()
{
char s[100];
int i,len;
printf("Enter the string..\n");
scanf("%[^\n]",s);
for(i=0;s[i]!='\0';i++);
len=i;
printf("Length of the string=%d",len);
}
 
Check whether the given string is palindrome(strrev will not work in gcc)
#include<stdio.h>
#include<string.h>
int main() {

char s[100],rs[100];
int l, i;
printf("Enter the string..\n");
gets(s);
strcpy(rs,s); // copying the string s to rs using strcpy function
 //reversing the string using built in function strrev
strrev(rs)
 //comparing the strings using strcmp function
if ( strcmp(s,rs)==0)
printf("String is palindrome")
else
printf("Not palindrome");
}

Palindrome checking -strrev and strcpy is done using a loop
#include<stdio.h>
#include<string.h>
int main() {

char s[100],rs[100];
int l, i,j;
printf("Enter the string..\n");
gets(s);
//reverse and copy
for(i=strlen(s)-1,j=0;i>=0;i--,j++)
  rs[j]=s[i];
  
  rs[j]='\0';
   
 //comparing the strings using strcmp function
 printf("Reversed string is \n");
 puts(rs);
if ( strcmp(s,rs)==0)
printf("String is palindrome");
else
printf("Not palindrome");
}
 
Palindrome checking without using built in functions( do not use string.h) ( university qn)
#include<stdio.h>
int main() {
char s[100],rs[100];
int flag=1, i,j,len=0;
printf("Enter the string..\n");
scanf("%[^\n]",s);
//check for palindrome
for(i=0;s[i]!='\0';i++,len++);//finding length of the string
printf("length of the string is %d\n",len);
for(i=0,j=len-1;i<=j;i++,j--)
  if(s[i]!=s[j]) {flag=0;break;}
 if ( flag)
    printf("String is palindrome\n");
else
   printf("Not palindrome\n");
}


Count the occurrence of a character in a string
#include <stdio.h>
#include <string.h>
void main()
{
char s[100],c;
int i,n=0;
printf("Enter a string...\n");
scanf("%[^\n]",s); // instead of gets(s)
printf("Enter the character to search...\n");
scanf(" %c",&c);  // leave a space before %c which will eat special characters
for(i=0;i<strlen(s);i++)
if(s[i]==c) n++;
printf("Number of occurrence=%d\n",n);
}
 Check whether the given character is present in a string ( university question)
#include <stdio.h>
#include <string.h>
void main()
{
char s[100],c;
int i,f=0;
printf("Enter a string...\n");
scanf("%[^\n]",s); // instead of gets(s)
printf("Enter the character to search...\n");
scanf(" %c",&c);  // leave a space before %c which will eat special characters
for(i=0;i<strlen(s);i++)
if(s[i]==c) {f=1;break;};
if(f)
printf("Given character is present in the string");
else
printf("Given Character is not present in the string\n");
}
 

Concatenating two strings with out using built in functions( university question)
#include <stdio.h>
int main()
{
  int i,j;
  char s1[100],s2[100];
  printf("Enter the string1...\n");
  scanf("%[^\n]",s1);
  getchar();
  printf("Enter the string2...\n");
  scanf("%[^\n]",s2);
   for(i=0;s1[i]!='\0';i++); // empty for loop for finding length
  for(i=i,j=0;s2[j]!='\0';j++,i++)
    s1[i]=s2[j];
  s1[i]='\0';
  printf("The concatenated string...:%s\n",s1);
}


Write a C program that sorts an array of strings alphabetically using strcmp() and strcpy() functions or Sorting list of names
#include <stdio.h>
#include <string.h>
main()
{
 char names[100][50],temp[50];
 int i,j,n;
 printf("Enter the number of names..\n");
 scanf("%d",&n);
 printf("Enter names..\n");
 for(i=0;i<n;i++)
  {
   getchar();
   scanf("%[^\n]",names[i]);
  }
 for(i=0;i<n-1;i++)
   for(j=0;j<n-1-i;j++)
     if (strcmp(names[j],names[j+1])>0)
       {
          strcpy(temp,names[i]);
          strcpy(names[i],names[j]);
          strcpy(names[j],temp);
        }
  printf("List of names in sorted order\n");
  for(i=0;i<n;i++)
    printf("%s\n",names[i]);
}
 
Count the   number of vowels, consonants , digits and spaces in a string.
#include <stdio.h>
int main()
{
    char str[150];
    int i, vowels, consonants, digits, spaces;
    vowels =  consonants = digits = spaces = 0;
    printf("Enter a  string: ");
    scanf("%[^\n]", str);
    for(i=0; str[i]!='\0'; ++i)
    {
        if(str[i]=='a' || str[i]=='e' || str[i]=='i' ||
           str[i]=='o' || str[i]=='u' || str[i]=='A' ||
           str[i]=='E' || str[i]=='I' || str[i]=='O' ||
           str[i]=='U')
        {
            ++vowels;
        }
        else if((str[i]>='a'&& str[i]<='z') || (str[i]>='A'&& str[i]<='Z'))
        {
            ++consonants;
        }
        else if(str[i]>='0' && str[i]<='9')
        {
            ++digits;
        }
        else if (str[i]==' ')
        {
            ++spaces;
        }
    }
    printf("Vowels: %d",vowels);
    printf("\nConsonants: %d",consonants);
    printf("\nDigits: %d",digits);
    printf("\nWhite spaces: %d\n", spaces);
}
 
Replacing a character with another in a string(university question)
#include <stdio.h>
#include <string.h>
int main()
{
  char s[100],c,nc;
  int i;
  printf("Enter the string..:\n");
  scanf("%[^\n]",s);
  printf("Enter the character to replace..\n");
  scanf(" %c",&c);
  printf("Enter the new character ....\n");
  scanf(" %c",&nc);
  for(i=0;i<strlen(s);i++)
  {
   if(s[i]==c)
       s[i]=nc;
  }
  printf("New string after replacement is \n");
  printf("%s\n",s);
}
 
Reverse a string with out using string functions.(uq)

#include <stdio.h>
int main()
{
    char str[150];
    char t;
    int i,j,len;
    printf("Enter a  string: ");
    scanf("%[^\n]", str);
    for(i=0;str[i]!='\0';i++);
    
    len=i;

    for(i=0,j=len-1;i<len/2;i++,j--)
     {
         t=str[i];
         str[i]=str[j];
         str[j]=t;
     }
     printf("reversed string is \n");
     printf("%s",str);
}

Write a C program that allows the user to enter a line of text, store it in an array, and then display it backward. The line length should be unspecified (terminated by pressing the Enter key), but assume it will not exceed 80 characters. ( university question)
#include <stdio.h>
#include <string.h>

#define MAX_LENGTH 80  // Maximum characters allowed

int main() {
    char line[MAX_LENGTH + 1];  // Array to store input (extra 1 for null terminator)

    printf("Enter a line of text (max 80 characters): ");
    fgets(line, sizeof(line), stdin);  // Read input including spaces
  size_t len=strlen(line);
   
    // Display the text in reverse
    printf("Reversed text: ");
    for (int i = len - 1; i >= 0; i--) {
        putchar(line[i]);
    }
    printf("\n");

    return 0;
}
Write a C program to find the number of words and lines in a given string.( University Question)
 Assumptions:
A word is a sequence of characters separated by spaces, tabs, or newlines.
A line ends with a newline character (\n)
#include <stdio.h>
#include <string.h>

int main() {
    char line[1000];
    char text[10000] = "";
    int lines = 0, words = 0, inWord = 0;

    printf("Enter multiple lines of text (press Enter on an empty line to stop):\n");

    while (1) {
        fgets(line, sizeof(line), stdin);

        // Check for empty line (only newline character)
        if (strcmp(line, "\n") == 0)
            break;

        strcat(text, line); // Append line to the full text
        lines++;
    }

    // Process the full text to count words
    for (int i = 0; text[i] != '\0'; i++) {
        if (text[i] != ' ' && text[i] != '\n' && text[i] != '\t') {
            if (inWord == 0) {
                inWord = 1;
                words++;
            }
        } else {
            inWord = 0;
        }
    }

    printf("\nNumber of lines: %d\n", lines);
    printf("Number of words: %d\n", words);

    return 0;
}
output:
Enter multiple lines of text (press Enter on an empty line to stop):
this is a test
counting lines and words

Number of lines: 2
Number of words: 8

Write a C program that reads a string from the user , counts the number of vowels , consonants, digits and special characters and display the counts separately
#include <stdio.h>
#include <ctype.h>

int main() {
    char str[1000];
    int vowels = 0, consonants = 0, digits = 0, specialChars = 0;

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin); // safer input method

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

        if (isalpha(ch)) {
            // Check if the character is a vowel
            ch = tolower(ch); // Normalize case
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
                vowels++;
            else
                consonants++;
        } else if (isdigit(ch)) {
            digits++;
        } else if (ch != '\n' && ch != ' ') {
            specialChars++;
        }
    }

    printf("Vowels: %d\n", vowels);
    printf("Consonants: %d\n", consonants);
    printf("Digits: %d\n", digits);
    printf("Special characters: %d\n", specialChars);

    return 0;
}
Output
Enter a string: this is test string with let675$%#$^*&(
Vowels: 6
Consonants: 17
Digits: 3
Special characters: 8

Write a C program to simulate  a simple login system where the user is prompted to enter a username and password . The program should
1.compare the entered credentials with predefined values( for eg username="admin" and password="1234")
2. Display success message if both match
3.Display an error message indicating that the login has failed if the credentials do not match
#include <stdio.h>
#include <string.h>

int main() {
    char username[20];
    char password[20];

    // Predefined credentials
    char correctUsername[] = "admin";
    char correctPassword[] = "1234";

    // User input
    printf("Enter username: ");
    scanf("%s", username);

    printf("Enter password: ");
    scanf("%s", password);

    // Compare credentials
    if (strcmp(username, correctUsername) == 0 &&
        strcmp(password, correctPassword) == 0) {
        printf("Login successful!\n");
    } else {
        printf("Login failed! Invalid username or password.\n");
    }

    return 0;
}

Output:

Enter username: admin
Enter password: 1234
Login successful!

programs to try
1.Read a string and print the characters backward.
2.check whether the given string is palindrome.(use built in functions)
3.count the occurrence of a character in a string.(uq)
4,Write a C program to read a sentence through keyboard and to display the count of white
spaces in the given sentence.(uq)
5.Write a C program to read an English Alphabet through keyboard and display whether
the given Alphabet is in upper case or lower case.(uq)
6.Without using any builtin string processing function like strlen, strcat etc., write a
program to concatenate two strings.(uq)
7.count the   number of vowels, consonants , digits and spaces in a string(uq)
8.Read list of names and sort the names in alphabetical order.
9.Toggle the case of every alphabet in the input string.
10.Write a C program to read an English Alphabet through keyboard and display whether
the given Alphabet is in upper case or lower case
11. Abbreviate a given string ( print first letter of each word).
12.Check for palindrome with out using built in functions.
13..Copy one string to another.
14.Count the number of words.
15.Print a substring ( read position and length)
16.Count all the occurrence of a  particular word.
17.Remove all occurrence of  a word from a sentence.
18.Check whether a word is present in a string.
19.Insert a word before a particular word.
20.Read a word and print the characters in alphabetical order.
21.Remove characters other than alphabet from a string
22.Reverse a string with out using string functions.(uq)
23.Find the length of a string without using built in functions(uq).

Comments

Popular posts from this blog

Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

Structure of a C Program

Single and Multi Dimensional Arrays