Site icon DataFlair

C String Functions with Examples

string functions in c

One of the most frequently used data types in all computer languages is the string. Strings are described in C as arrays of characters that end in the null character “0.” Writing C programs that store, manipulate, or communicate textual data requires proper string handling.

Explanation of Strings in C

Strings are kept in C as arrays of the char data type. A string’s characters each take up one byte of memory. The string’s final character is always the null terminator ‘0’ to indicate the string’s end. For instance:

char str[6] = {'H','e','l','l','o','\0'};

Here, str is an array of 6 characters, including the null terminator. The length of this string is 5 (excluding null).

We can also declare strings like this:

char str[6] = "Hello";

The compiler automatically appends the ‘\0’ at the end.

Strings in C can be initialized but cannot be assigned. For example:

str = "World"; // Error

This is because arrays cannot be assigned in C. We need to use string functions like strcpy() for assignments.

Importance of String Handling in C

Basic String Functions in C

C provides a wide range of built-in functions for manipulating strings. Here are some commonly used basic string functions.

Function Description
strlen(string) Calculates and gives back the number of characters in the provided string
strcpy(destination, source) Takes the contents of the source string and puts them into the destination string
strcat(first_string, second_string) Joins first_string and second_string together. The combined string is put into first_string.
strcmp(first_string, second_string) Evaluate first_string and second_string to check if they are the same. Returns 0 if they match exactly.
strrev(string) Flips the order of the characters in the string and gives back the reversed version
strlwr(string) Alters the string so all characters are in lowercase, then returns the lowercase string
strupr(string) Alters the string so all characters are in uppercase, then returns the uppercase string
strlen() Returns back the length of the provided string
strnlen() Gives back the length specified if it is less than the string length; otherwise, it gives the full string length
strcmp() Assesses two strings and returns 0 if they match exactly
strncmp() Compares only the first n characters of the two strings
strcat() Joins two strings together and returns the combined string
strncat() Joins the first n characters of one string onto the end of another string
strcpy() Copies the contents of one string into a different string
strncpy() Copies only the first n characters from one string into another string
strchr() Finds the first instance of a given character within a string
strrchr() Finds the last instance of a given character within a string
strstr() Finds the first instance of a given substring within a string
strnstr() Finds the first instance of a given substring in a string, searching only the first n characters
strcasecmp() Compares two strings, ignoring the difference in capitalization
strncasecmp() Compares only the first n characters of two strings, ignoring differences in capitalization

strlen() – Finding String Length

Syntax

size_t strlen(const char *str);

Purpose and Description

Example

#include <stdio.h>
#include <string.h>

int main() {
  char str[50] = "Hello, World!";

  int len = strlen(str);

  printf("Length of the string is: %d", len);
  
  return 0;
}
Output: Length of the string is: 13

strcpy() – Copying Strings

Syntax

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

Purpose and Description

Example

#include <stdio.h>
#include <string.h>

int main() {
  
  char source[20] = "Hello";
  char destination[20];

  // Copies source to destination
  strcpy(destination, source);

  printf("Destination string: %s", destination);

  return 0;
}
Output: Destination string: Hello

strcat() – Concatenating Strings

Syntax

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

Purpose and Description

Example

#include <stdio.h>
#include <string.h>

int main() {

  char destination[30] = "Hello";
  char source[15] = "World";

  // Concatenates source to destination
  strcat(destination, source);

  printf("Destination string: %s", destination);

  return 0;
}
Output: Destination string: HelloWorld

strcmp() – Comparing Strings

Syntax

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

Purpose and Description

Example

#include <stdio.h>
#include <string.h>

int main() {

  char str1[15];
  char str2[15];
  
  strcpy(str1, "Apple");
  strcpy(str2, "Mango");

  int result = strcmp(str1, str2);
  
  if(result == 0) {
    printf("Strings are equal");
  } else if(result > 0) {
    printf("str1 is greater than str2"); 
  } else {
    printf("str1 is less than str2");
  }
  
  return 0;
}
Output: str1 is less than str2

Additional String Functions in C

Here are some more useful string functions provided in C.

strchr() – Finding a Character in a String

Syntax

char *strchr(const char *str, int character);

Purpose and Description

Example

#include <stdio.h>
#include <string.h>

int main() {

  char str[50] = "Hello, World!";
  char *result;

  result = strchr(str, 'W');
  
  if(result) {
    printf("Character found at %ld", result-str);
  } else {
    printf("Character not found");
  }

  return 0;
}
Output: Character found at 7

strstr() – Finding a Substring in a String

Syntax

char *strstr(const char *str, const char *substr);

Purpose and Description

Example

#include <stdio.h>
#include <string.h>

int main() {

  char str[100] = "Hello, World!";
  char *result;
  
  result = strstr(str, "World");
  
  if(result) {
    printf("Substring found at %ld", result-str); 
  } else {
    printf("Substring not found");
  }
  
  return 0;
}

Output: Substring found at 7

strtok() – Tokenizing Strings

Syntax

char *strtok(char *str, const char *delimiter);

Purpose and Description

  • strtok() breaks the given string into tokens separated by the delimiter character(s).
  • In the first call, it expects the string argument str. In subsequent calls, use NULL for str.
  • It returns a pointer to the next token in the string.
  • When no token is left, it returns NULL.

Example

#include <stdio.h>
#include <string.h>

int main() {

  char str[100] = "Hello, This is a test";
  char *token;

  // First call
  token = strtok(str, " "); 
  while(token != NULL) {
    printf("%s\n", token);
    
    // Subsequent calls
    token = strtok(NULL, " "); 
  }
  
  return 0;
}
Output:

Hello,
This
is
a
test

puts() and gets() – Input and Output Functions

Syntax and Purpose

puts() – Outputs a string to stdout and appends a new line.
gets() – Reads a string from stdin till newline.

Example for puts()

#include <stdio.h>

int main() {

  char str[] = "Hello, World!";
  
  puts(str);
  
  return 0;
}
Output:

Hello, World!

Example for gets()

#include <stdio.h>

int main() {

  char str[100];

  printf("Enter a string: ");
  gets(str);

  printf("You entered: %s", str);
  
  return 0;
}

Input: Hello, World!

Output: You entered: Hello, World!

strlwr() / strupr() – Convert Strings to Lowercase / Uppercase

Syntax and Purpose

strlwr() converts a string to lowercase.
strupr() converts a string to uppercase

Example for strlwr()

#include <stdio.h>
#include <string.h>

int main() {

  char str[20] = "Hello WORLD"; 
  strlwr(str);
  
  printf("Lowercase string: %s", str);

  return 0;
}
Output: Lowercase string: hello world

Example for strupr()

#include <stdio.h>
#include <string.h>

int main() {

  char str[20] = "Hello world";
  strupr(str);

  printf("Uppercase string: %s", str);

  return 0;  
}
Output: Uppercase string: HELLO WORLD

strrev() – Reverse a String

Syntax and Purpose

strrev() reverses the given null-terminated string.

Example

#include <stdio.h>
#include <string.h>

int main() {

  char str[50] = "Hello, World!";

  strrev(str);
  
  printf("Reversed string: %s", str);

  return 0;
}
Output: Reversed string: !dlroW ,olleH

Performance Considerations

Optimizing string operations can significantly improve program efficiency.

Optimizing String Operations

  • Use pointer notation instead of array notation wherever possible.
  • Use stack allocation instead of dynamic allocation if string sizes are known.
  • Use char arrays instead of printf() where feasible.
  • Use strnxxx() functions instead of strxxx() to avoid buffer overflows.
  • Use const pointers for strings that won’t change.

Memory Allocation Strategies

  • Allocate string buffer size dynamically where possible.
  • Use optimal string size to avoid large unused buffers.
  • Reuse already allocated buffers instead of allocating new ones.
  • Free buffers promptly after use for better memory utilization.

Use Cases and Examples

Here are some examples of string usage in real-world C programs:

  • File I/O – Reading data from files into character arrays, parsing filenames, paths etc.
  • Networking – Transmitting textual data over sockets, parsing URLs, and formatting network packets.
  • Databases – Storing, retrieving and filtering data from databases.
  • Web servers – Handling HTTP requests, and generating HTML or JSON output.
  • Command-line interfaces – Reading user input, printing formatted output to console.
  • Text editors – Managing entire documents in memory, searching and replacing.

Conclusion

String handling is essential in C for storing, processing and communicating text-based data. This article covered C’s string representation, standard string functions, advanced manipulation, multibyte strings, performance optimization, and real-world applications across domains. Robust string functions make C suitable for diverse text-processing tasks.

Exit mobile version