How to Slice String in C Language?

  • Home
  • C
  • How to Slice String in C Language?

Everywhere you can read that c is too powerful language. But i want to add one more line with it. C is Powerful language if you know how to use it. Here we have a problem which we need to clear out.

How to Slice String in C Language?

lets we take input from user and if string length is greater than 10 we slice first 5 string and print out next 5 string to the console.

We will need to function that we custom create without string functions that available in c library. One is string length checker and 2nd is to slice string.

stringLength function

Its return the length of string that is entered by user so we can know that length is greater than 10 or not

CCopy
int stringLength(const char str[])
{
    int count = 0;
    while (str[count] != '\0')
    {
        ++count;
    }
    return count;
}

now we need a slice function that slice our string .

sliceString Function

CCopy
char *sliceString(char *str, int start, int end)
{

    int i;
    int size = (end - start) + 2;
    char *output = (char *)malloc(size * sizeof(char));

    for (i = 0; start <= end; start++, i++)
    {
        output[i] = str[start];
    }

    output[size] = '\0';

    return output;
}

After these we need to implement our code to the main function.

CCopy
int main()
{

    char str[256];
    char slicedOutput[256];

    printf("\nEnter Your String : ");
    scanf("%s", str);

    if (stringLength(str) > 10)
    {
        printf("\nSliced Output is : %s", sliceString(str, 5, 9));
    }
    else
    {
        printf("\nYour Input string is : %s", str);
    }

    return 0;
}

Finally we got the answer how to slice string in c language with our custom functions.

Whole File

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

int stringLength(const char str[])
{
    int count = 0;
    while (str[count] != '\0')
    {
        ++count;
    }
    return count;
}

char *sliceString(char *str, int start, int end)
{

    int i;
    int size = (end - start) + 2;
    char *output = (char *)malloc(size * sizeof(char));

    for (i = 0; start <= end; start++, i++)
    {
        output[i] = str[start];
    }

    output[size] = '\0';

    return output;
}

int main()
{

    char str[256];
    char slicedOutput[256];

    printf("\nEnter Your String : ");
    scanf("%s", str);

    if (stringLength(str) > 10)
    {
        printf("\nSliced Output is : %s", sliceString(str, 5, 9));
    }
    else
    {
        printf("\nYour Input string is : %s", str);
    }

    return 0;
}

Leave a Comment