How to Slice String in C Language?

The Test Coder
2 min readOct 28, 2021

--

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.

How to Reverse Integer in C Language?

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

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

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.

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

#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;
}

--

--