Join Regular Classroom : Visit ClassroomTech

Data Structure – codewindow.in

Related Topics

Data Structure

How to find the index of a specific character or substring in a string in C?

In C, the standard library provides several functions to find the index of a specific character or substring in a string:

  1. strchr: This function finds the first occurrence of a character in a string and returns a pointer to that character. If the character is not found, the function returns NULL.

char *strchr(const char *str, int c);
  1. strstr: This function finds the first occurrence of a substring in a string and returns a pointer to the beginning of that substring. If the substring is not found, the function returns NULL.

char *strstr(const char *haystack, const char *needle);
  1. strpbrk: This function finds the first occurrence of any character from a set of characters in a string and returns a pointer to that character. If none of the characters in the set are found, the function returns NULL.

char *strpbrk(const char *str, const char *charset);

To find the index of a character or substring, you can subtract the pointer returned by the above functions from the original string pointer to get the index:

const char *str = "Hello, world!";
char *ptr = strchr(str, 'o');
if (ptr != NULL) {
    printf("Index of 'o': %d\n", (int) (ptr - str));
}

char *substr = "world";
ptr = strstr(str, substr);
if (ptr != NULL) {
    printf("Index of 'world': %d\n", (int) (ptr - str));
}

How to extract a substring from a string in C?

In C, there is no built-in function for extracting a substring from a string. However, it can be achieved by creating a new string and copying the desired characters from the original string.

Here’s an example code that extracts a substring of length len starting from index start of string str and returns the extracted substring:

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

char* substring(char* str, int start, int len) {
    char* sub = malloc(len+1); // allocate memory for substring
    int i;
    for (i = 0; i < len; i++) {
        sub[i] = str[start+i];
    }
    sub[len] = '\0'; // add null terminator
    return sub;
}

You can call the substring function as follows:

char* str = "Hello, World!";
char* sub = substring(str, 7, 5); // extracts "World"
printf("%s", sub);
free(sub); // free memory allocated for substring

How to split a string in C using a specific delimiter?

In C, there is no built-in function for splitting a string using a specific delimiter. However, you can write your own function to split a string. Here is an example function that splits a string using a specific delimiter:

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

#define MAX_TOKENS 100

void split(char *string, char *delimiter, char **tokens, int *num_tokens)
{
    char *token;
    token = strtok(string, delimiter);
    while (token != NULL && *num_tokens < MAX_TOKENS) {
        tokens[*num_tokens] = token;
        (*num_tokens)++;
        token = strtok(NULL, delimiter);
    }
}

int main()
{
    char string[] = "apple,banana,orange";
    char delimiter[] = ",";
    char *tokens[MAX_TOKENS];
    int num_tokens = 0;

    split(string, delimiter, tokens, &num_tokens);

    for (int i = 0; i < num_tokens; i++) {
        printf("%s\n", tokens[i]);
    }

    return 0;
}

In this example, the split function takes in a string, a delimiter, an array of tokens, and a pointer to an integer for the number of tokens. The function uses the strtok function to split the string into tokens based on the delimiter. The tokens are stored in the tokens array, and the number of tokens is stored in the num_tokens variable. The main function uses the split function to split a string containing the names of fruits separated by commas. The printf function is then used to print out each fruit name on a new line.

What is the difference between a string and a string builder in C?

C does not have a built-in string builder class like Java, but there are several libraries that provide similar functionality. In C, a string is a sequence of characters stored in an array of characters terminated by a null character (‘\0’). Strings in C are immutable, meaning that once a string is created, its contents cannot be changed.

A string builder, on the other hand, is a class in Java that provides a mutable sequence of characters. You can append, insert, delete, and replace characters in a string builder object. In C, you can achieve similar functionality by dynamically allocating memory for a character array and manipulating it using standard C library functions such as strcat(), strncat(), strcpy(), strncpy(), strlen(), etc. However, this requires more effort and is more error-prone than using a string builder in Java.

How to declare and initialize a string builder in C?

In C programming language, there is no built-in string builder data structure. However, we can use a character array as a string builder and perform operations on it.

To declare and initialize a character array as a string builder in C, we can use the following syntax:

char str_builder[100]; // declare a character array of size 100 as a string builder
str_builder[0] = '\0'; // initialize the array with null character

In the above code, we declare a character array of size 100 and initialize it with a null character. The null character is used to mark the end of the string builder.

Alternatively, we can use a pointer to a character array and dynamically allocate memory for the string builder as shown below:

char *str_builder = malloc(100 * sizeof(char)); // dynamically allocate memory for the string builder
str_builder[0] = '\0'; // initialize the array with null character

In the above code, we use the malloc() function to allocate memory for the string builder. We allocate 100 bytes of memory using the sizeof(char) operator, which is equivalent to the size of a single character in bytes. We then initialize the array with a null character.

After performing operations on the string builder, we need to deallocate the memory using the free() function as shown below:

free(str_builder); // deallocate memory for the string builder

This is important to prevent memory leaks in our program.

How to append to a string builder in C?

In C, there is no built-in data type called “string builder”, but we can simulate its functionality using a character array and manipulating its size as needed. Here’s an example of how to append a string to a character array in C:

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

int main() {
    char str[20] = "Hello";
    
    // append a string to str
    strcat(str, " world!");

    printf("%s", str); // output: Hello world!
    
    return 0;
}

In the above code, we use the strcat() function from the string.h library to append the string ” world!” to the end of the str array. The strcat() function concatenates two strings by copying the second string to the end of the first string, and adding a null terminator at the end.

How to insert into a string builder in C?

C does not have a built-in string builder data structure like Java, but you can simulate its functionality using dynamic memory allocation and string manipulation functions.

Here is an example of how you can implement a basic string builder in C:

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

typedef struct {
    char* buffer;
    size_t length;
    size_t capacity;
} StringBuilder;

void StringBuilder_Init(StringBuilder* builder) {
    builder->buffer = malloc(1);
    builder->length = 0;
    builder->capacity = 1;
    builder->buffer[0] = '\0';
}

void StringBuilder_Append(StringBuilder* builder, const char* str) {
    size_t len = strlen(str);
    size_t new_length = builder->length + len;
    if (new_length + 1 > builder->capacity) {
        builder->capacity = new_length + 1;
        builder->buffer = realloc(builder->buffer, builder->capacity);
    }
    strcat(builder->buffer, str);
    builder->length = new_length;
}

void StringBuilder_Insert(StringBuilder* builder, int index, const char* str) {
    size_t len = strlen(str);
    if (index < 0 || (size_t)index > builder->length) {
        return;
    }
    size_t new_length = builder->length + len;
    if (new_length + 1 > builder->capacity) {
        builder->capacity = new_length + 1;
        builder->buffer = realloc(builder->buffer, builder->capacity);
    }
    memmove(builder->buffer + index + len, builder->buffer + index, builder->length - index + 1);
    memcpy(builder->buffer + index, str, len);
    builder->length = new_length;
}

void StringBuilder_Delete(StringBuilder* builder, int start_index, int length) {
    if (start_index < 0 || (size_t)start_index >= builder->length || length < 0) {
        return;
    }
    if ((size_t)start_index + length > builder->length) {
        length = builder->length - start_index;
    }
    memmove(builder->buffer + start_index, builder->buffer + start_index + length, builder->length - start_index - length + 1);
    builder->length -= length;
}

void StringBuilder_Destroy(StringBuilder* builder) {
    free(builder->buffer);
    builder->buffer = NULL;
    builder->length = 0;
    builder->capacity = 0;
}

int main() {
    StringBuilder builder;
    StringBuilder_Init(&builder);
    StringBuilder_Append(&builder, "Hello, ");
    StringBuilder_Append(&builder, "world!");
    printf("%s\n", builder.buffer);
    StringBuilder_Insert(&builder, 7, "awesome ");
    printf("%s\n", builder.buffer);
    StringBuilder_Delete(&builder, 0, 7);
    printf("%s\n", builder.buffer);
    StringBuilder_Destroy(&builder);
    return 0;
}

In this example, we use a struct to represent the string builder, with fields for the buffer, length, and capacity. The StringBuilder_Init function initializes the buffer with a single null terminator character. The StringBuilder_Append function appends a string to the end of the buffer, resizing the buffer if necessary. The StringBuilder_Insert function inserts a string at a specified index, moving the existing characters to make room for the new string. The StringBuilder_Delete function removes a substring from the buffer, shifting the remaining characters to fill the gap. The StringBuilder_Destroy function frees the memory allocated for the buffer.

Questions on Chapter 2

Questions on Chapter 2

      

We Love to Support you

Go through our study material. Your Job is awaiting.

Recent Posts
Categories

Explain any important feature of OOPs

Explain any important feature of OOPs

Explain any important feature of OOPs