String Practice Question in C

Q: Which of the following is used to appropriately read a multi-word string.

1. gets()

2. puts()

3. printf()

4. scanf()

The correct answer is: 1. gets()

Explanation of Options:

  1. gets():

    • The gets() function reads an entire line of input (including spaces) until a newline (\n) character is encountered.
    • This makes it suitable for reading multi-word strings.
    • Important Note: gets() is unsafe and has been deprecated in C11 because it does not perform bounds checking, potentially causing buffer overflows.
  2. puts():

    • The puts() function is used for printing strings, not reading them.
    • It appends a newline character (\n) after the string is printed.
  3. printf():

    • The printf() function is for formatted output, not input.
    • It cannot be used to read strings.
  4. scanf():

    • The scanf() function is used to read formatted input.
    • However, when used with %s, it stops reading at the first whitespace (space, tab, or newline), making it unsuitable for reading multi-word strings.

Modern Alternative to gets():

To safely read multi-word strings, use fgets(), which allows bounds checking:

#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);  // Reads a multi-word string safely
    printf("You entered: %s", str);
    return 0;
}


Q:  Write a program to take string as an input from the user using %c and %s confirm that the strings are equal.

#include <stdio.h>

int main() {
    printf("Enter string: ");
    char str[10];
    // input using '%s'
    // scanf("%s", str);

    // input using '%c'
    for(int i=0; i<9; i++){
        scanf("%c", &str[i]);
        fflush(stdin); // does not count 'enter key'.
    }
    str[10] = '\0';

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

Q: Write your own version of strlen function from <string.h>.

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

int my_strlen(char[]);

int main() {
    // char arr[] = "Hello World";
    char arr[100];
    printf("Enter a string: ");
    fgets(arr, sizeof(arr) ,stdin);
    
    // Remove newline character if it exists
    size_t len = strlen(arr);
    if (len > 0 && arr[len - 1] == '\n') {
        arr[len - 1] = '\0';
    }
    printf("In-build function, length of a string is %d\n", strlen(arr));
    printf("User-build function, length of a string is %d\n", my_strlen(arr));
    return 0;
}

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

  • size_t is an unsigned integer data type that is defined in various header files such as:

<stddef.h>, <stdio.h>, <stdlib.h>, <string.h>, <time.h>, <wchar.h>

  • It’s a type which is used to represent the size of objects in bytes and is therefore used as the return type by the sizeof.

Q: Write a function slice() to slice a string. It should change the original string such that it is now the sliced string. Take ‘m’ and ‘n’ as the start and ending position for slice.

#include <stdio.h>

void my_slice(char arr[], int start, int end);
int my_strlen(char arr[]);

int main() {
    char arr[100];
    int start, end;

    printf("Enter string: ");
    fgets(arr, sizeof(arr), stdin);
    printf("Enter starting and ending index\n");
    printf("Tip: use \"my_strlen(arr)\" for geting last index of the string.\n");
    scanf("%d %d", &start, &end);
    my_slice(arr, start, end);
    printf("%s", arr);
    return 0;
}

void my_slice(char arr[], int start, int end) {
    int i = 0, j = 0;

    while (arr[i] !='\0') {
        if(i>=start && i<=end) {
            arr[j++] = arr[i];
        }
        i++;
    }
    arr[j] = '\0';
}

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

OR

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

void slice(char *str, int m, int n) {
    // Ensure valid indices
    int len = strlen(str);
    if (m < 0 || n >= len || m > n) {
        printf("Invalid slicing indices.\n");
        return;
    }

    // Shift characters to start from index m and end at index n
    int i, j = 0;
    for (i = m; i <= n; i++) {
        str[j++] = str[i];
    }
    str[j] = '\0'; // Null-terminate the sliced string
}

int main() {
    char str[100];
    int m, n;

    // Input the string
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '\0'; // Remove newline character from input

    // Input indices for slicing
    printf("Enter the start index (m): ");
    scanf("%d", &m);
    printf("Enter the end index (n): ");
    scanf("%d", &n);

    // Perform slicing
    slice(str, m, n);

    // Print the result
    printf("Sliced string: %s\n", str);

    return 0;
}

OR

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

void my_slice(char arr[], int start, int end);
int my_strlen(char arr[]);

int main() {
    // printf("Enter string: ");

    char arr[] = "Hello World";
    // char arr[100];
    // fgets(arr, sizeof(arr), stdin);
    
    int length = my_strlen(arr);
    char result[length + 1]; // Buffer to store sliced result
    
    my_slice(arr, 6, length);
    printf("Sliced string: %s\n", arr);
    
    return 0;
}

void my_slice(char arr[], int start, int end) {
    int j = 0;
    for (int i = start; i < end && arr[i] != '\0'; i++) {
        arr[j++] = arr[i];
    }
    arr[j] = '\0'; // Null-terminate the resulting string
}

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

OR

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

void my_slice(char arr[], int start, int end, char result[]);
int my_strlen(char arr[]);

int main() {
    // printf("Enter string: ");

    char arr[] = "Hello World";
    // char arr[100];
    // fgets(arr, sizeof(arr), stdin);
    
    int length = my_strlen(arr);
    char result[length + 1]; // Buffer to store sliced result
    
    my_slice(arr, 6, length, result);
    printf("Sliced string: %s\n", result);
    
    return 0;
}

void my_slice(char arr[], int start, int end, char result[]) {
    int j = 0;
    for (int i = start; i < end && arr[i] != '\0'; i++) {
        result[j++] = arr[i];
    }
    result[j] = '\0'; // Null-terminate the resulting string
}

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


Q: Write your own version of strcpy function from <string.h>.

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

void my_strcpy(char* destination, char* source);

int main() {
    char arr[] = "Hello World!";
    char arr1[strlen(arr) + 1]; // +1 to account for the null terminator

    my_strcpy(arr1, arr);
    printf("%s", arr1);

    return 0;
}

void my_strcpy(char* destination, char* source) {
    int i = 0;

    while (source[i] != '\0') {
        destination[i] = source[i];
        i++;
    }
    destination[i] = '\0'; // Add the null terminator
}


Q: Write a program to encrypt and decrypt a string by adding 1 to the ascii value of its characters.

#include <stdio.h>

void my_strencrypt(char* str);
void my_strdecrypt(char* str);

int main() {
    char str[50] = "Hello World!";
    
    my_strencrypt(str);
    printf("Encrypted: %s\n", str);

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

    return 0;
}

void my_strencrypt(char* str) {
    int i = 0;

    while (str[i] != '\0') {
        str[i++] += 1;
    }
}

void my_strdecrypt(char* str) {
    int i = 0;

    while (str[i] != '\0') {
        str[i++] -= 1;
    }
}

Other:

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

void my_strencrypt(char* str, int n, char key);
void my_strdecrypt(char* str, int n);
void input_validation(char* str, int n);

int main() {
    char str[50] = "Hello World!"; // Ensure the buffer is large enough
    int n = 4;
    char key = 'z';

    input_validation(str, n);

    my_strencrypt(str, n, key);
    printf("Encrypted: %s\n", str);

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

    return 0;
}

void my_strencrypt(char* str, int n, char key) {
    char temp[strlen(str) + 1]; // Temporary buffer to hold the modified string
    int i = 0, j = 0;

    while (str[i] != '\0') {
        if (j == n) {
            temp[j++] = key; // Insert the key at the nth position
        }
        temp[j++] = str[i++]; // Copy the original string character
    }

    temp[j] = '\0'; // Null-terminate the string
    strcpy(str, temp); // Copy the modified string back to `str`
}

void my_strdecrypt(char* str, int n) {
    int i = 0, j = 0;

    while (str[i] != '\0') {
        if (i == n) {
            i++; // Skip the inserted key character
        }
        str[j++] = str[i++]; // Copy the rest of the string
    }

    str[j] = '\0'; // Null-terminate the string
}

void input_validation(char* str, int n) {
    int len = strlen(str);
        if (n < 0 || n >= len) {
            printf("Invalid position for decryption.\n");
            return;
        }
}


Q: Write a program to count the occurrence of a given character in a string.

#include <stdio.h>

int main() {
    char str[] = "hello World";
    int count = 0, i = 0;
    char find = 'l';

    // while(str[i] != '\0') {
    //     if(str[i] == find){
    //         count++;
    //     }
    //     i++;
    // }

    // OR
    for(i=0; str[i] != '\0'; i++) {
        if(str[i] == find){
            count++;
        }
    }

    printf("Occurrence of %c is %d", find, count);
    return 0;
}


Q:  Write a program to check whether a given character is present in a string or not.

#include <stdio.h>

int main() {
    char str[] = "hello World";
    char find = 'l';

    for(i=0; str[i] != '\0'; i++) {
        if(str[i] == find) {
            printf("Character '%c' is present in the string at index %d.\n", str[i], i);
            break;
        }
    }

    return 0;
}




#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);  // Reads a multi-word string safely
    printf("You entered: %s", str);
    return 0;
}


#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);  // Reads a multi-word string safely
    printf("You entered: %s", str);
    return 0;
}


#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);  // Reads a multi-word string safely
    printf("You entered: %s", str);
    return 0;
}


#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);  // Reads a multi-word string safely
    printf("You entered: %s", str);
    return 0;
}


#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);  // Reads a multi-word string safely
    printf("You entered: %s", str);
    return 0;
}


#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);  // Reads a multi-word string safely
    printf("You entered: %s", str);
    return 0;
}


#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);  // Reads a multi-word string safely
    printf("You entered: %s", str);
    return 0;
}


#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);  // Reads a multi-word string safely
    printf("You entered: %s", str);
    return 0;
}


#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);  // Reads a multi-word string safely
    printf("You entered: %s", str);
    return 0;
}


#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);  // Reads a multi-word string safely
    printf("You entered: %s", str);
    return 0;
}


#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);  // Reads a multi-word string safely
    printf("You entered: %s", str);
    return 0;
}


#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);  // Reads a multi-word string safely
    printf("You entered: %s", str);
    return 0;
}














































Post a Comment

0 Comments