Virtual assistance

C Programming Tutorial

Welcome to AIVista --India's tutorial pages on C Programming

C Programming

Strings in C

Strings in C are arrays of characters terminated by a null character ('\0'). Learn how to work with character arrays and string functions.

"In C, a string is just an array of characters with a null terminator at the end - simple yet powerful!"

What is a String in C?

A string in C is a sequence of characters stored in consecutive memory locations and terminated by a null character ('\0'). Strings are essentially character arrays with a special ending marker.

String Declaration and Initialization

Character Array Declaration

// Different ways to declare strings
char str1[20];                    // Uninitialized string
char str2[20] = "Hello World";    // Initialized with string literal
char str3[] = "AIVista India";    // Size determined automatically
char str4[6] = {'H', 'e', 'l', 'l', 'o', '\0'};  // Character by character

String Input and Output

#include <stdio.h>

int main() {
    char name[50];

    // Input a string
    printf("Enter your name: ");
    scanf("%s", name);  // Reads until whitespace

    // Output a string
    printf("Hello, %s!\n", name);

    // Using fgets for full lines
    char sentence[100];
    printf("Enter a sentence: ");
    fgets(sentence, sizeof(sentence), stdin);
    printf("You entered: %s", sentence);

    return 0;
}

String Functions

C provides several built-in string functions in the <string.h> header file.

strlen() - String Length

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

int main() {
    char str[] = "AIVista India";
    int length = strlen(str);

    printf("String: %s\n", str);
    printf("Length: %d characters\n", length);

    return 0;
}

strcpy() - String Copy

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

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

    strcpy(destination, source);

    printf("Source: %s\n", source);
    printf("Destination: %s\n", destination);

    return 0;
}

strncpy() - Safe String Copy

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

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

    // Copy only first 9 characters (leaving space for null terminator)
    strncpy(destination, source, 9);
    destination[9] = '\0';  // Ensure null termination

    printf("Source: %s\n", source);
    printf("Destination: %s\n", destination);

    return 0;
}

strcat() - String Concatenation

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

int main() {
    char str1[50] = "Hello";
    char str2[] = " World";

    strcat(str1, str2);

    printf("Concatenated string: %s\n", str1);

    return 0;
}

strncat() - Safe String Concatenation

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

int main() {
    char str1[20] = "Hello";
    char str2[] = " World Program";

    // Concatenate only first 6 characters of str2
    strncat(str1, str2, 6);

    printf("Result: %s\n", str1);

    return 0;
}

strcmp() - String Comparison

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

int main() {
    char str1[] = "Apple";
    char str2[] = "Banana";
    char str3[] = "Apple";

    // Compare strings
    int result1 = strcmp(str1, str2);
    int result2 = strcmp(str1, str3);

    printf("strcmp('%s', '%s') = %d\n", str1, str2, result1);
    printf("strcmp('%s', '%s') = %d\n", str1, str3, result2);

    // Interpretation
    if (result1 < 0) {
        printf("%s comes before %s\n", str1, str2);
    } else if (result1 > 0) {
        printf("%s comes after %s\n", str1, str2);
    } else {
        printf("%s and %s are equal\n", str1, str2);
    }

    return 0;
}

strncmp() - Compare First n Characters

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

int main() {
    char str1[] = "Hello World";
    char str2[] = "Hello Universe";

    // Compare only first 5 characters
    int result = strncmp(str1, str2, 5);

    printf("Comparing first 5 chars: %d\n", result);
    if (result == 0) {
        printf("First 5 characters are identical\n");
    }

    return 0;
}

String Manipulation Functions

strchr() - Find Character in String

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

int main() {
    char str[] = "Hello World";
    char *ptr;

    // Find first occurrence of 'o'
    ptr = strchr(str, 'o');

    if (ptr != NULL) {
        printf("Found 'o' at position: %ld\n", ptr - str);
        printf("Remaining string: %s\n", ptr);
    } else {
        printf("Character not found\n");
    }

    return 0;
}

strstr() - Find Substring

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

int main() {
    char str[] = "Hello World Program";
    char *ptr;

    // Find substring "World"
    ptr = strstr(str, "World");

    if (ptr != NULL) {
        printf("Found 'World' at position: %ld\n", ptr - str);
        printf("Found substring: %s\n", ptr);
    } else {
        printf("Substring not found\n");
    }

    return 0;
}

Custom String Functions

Custom String Length Function

#include <stdio.h>

int my_strlen(char str[]) {
    int length = 0;
    while (str[length] != '\0') {
        length++;
    }
    return length;
}

int main() {
    char str[] = "AIVista India";
    printf("Length of '%s' is %d\n", str, my_strlen(str));
    return 0;
}

Custom String Copy Function

#include <stdio.h>

void my_strcpy(char dest[], char src[]) {
    int i = 0;
    while (src[i] != '\0') {
        dest[i] = src[i];
        i++;
    }
    dest[i] = '\0';  // Add null terminator
}

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

    my_strcpy(destination, source);

    printf("Source: %s\n", source);
    printf("Destination: %s\n", destination);

    return 0;
}

String Reversal

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

void reverse_string(char str[]) {
    int start = 0;
    int end = strlen(str) - 1;

    while (start < end) {
        // Swap characters
        char temp = str[start];
        str[start] = str[end];
        str[end] = temp;

        start++;
        end--;
    }
}

int main() {
    char str[] = "AIVista India";

    printf("Original: %s\n", str);
    reverse_string(str);
    printf("Reversed: %s\n", str);

    return 0;
}

Common String Problems

1. Check if String is Palindrome

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

int is_palindrome(char str[]) {
    int start = 0;
    int end = strlen(str) - 1;

    while (start < end) {
        // Skip non-alphanumeric characters
        while (start < end && !isalnum(str[start])) start++;
        while (start < end && !isalnum(str[end])) end--;

        // Compare characters (case insensitive)
        if (tolower(str[start]) != tolower(str[end])) {
            return 0;  // Not a palindrome
        }

        start++;
        end--;
    }

    return 1;  // Is a palindrome
}

int main() {
    char str[] = "A man, a plan, a canal: Panama";

    if (is_palindrome(str)) {
        printf("'%s' is a palindrome\n", str);
    } else {
        printf("'%s' is not a palindrome\n", str);
    }

    return 0;
}

2. Count Words in a String

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

int count_words(char str[]) {
    int count = 0;
    int in_word = 0;

    for (int i = 0; str[i] != '\0'; i++) {
        if (isspace(str[i])) {
            in_word = 0;
        } else if (in_word == 0) {
            in_word = 1;
            count++;
        }
    }

    return count;
}

int main() {
    char str[] = "Welcome to AIVista India";

    printf("String: %s\n", str);
    printf("Word count: %d\n", count_words(str));

    return 0;
}

Advantages of Strings in C

  • Simple and efficient for text manipulation
  • Direct memory access and control
  • Compatible with C's low-level nature
  • Rich library of string functions

Limitations and Precautions

  • No built-in bounds checking (buffer overflow risk)
  • Manual memory management required
  • Null termination must be handled carefully
  • String operations can be error-prone

Best Practices

  • Always allocate enough space for strings (including null terminator)
  • Use safe functions like strncpy() and strncat() when possible
  • Check for NULL pointers before using string functions
  • Include <string.h> header for string functions
  • Be aware of buffer overflow vulnerabilities
  • Use fgets() instead of gets() for input

Conclusion

Strings are fundamental to C programming and understanding them is crucial for text processing. While C strings can be tricky due to manual memory management, they provide the control and efficiency that makes C powerful. Practice with different string operations to become proficient in string manipulation! 🚀