How to cut part of a string in c?
c, cut, string
Solution
The following function cuts a given range out of a char buffer. The range is identified by startng index and length. A negative length may be specified to indicate the range from the starting index to the end of the string.
/*
* Remove given section from string. Negative len means remove
* everything up to the end.
*/
int str_cut(char *str, int begin, int len)
{
int l = strlen(str);
if (len < 0) len = l - begin;
if (begin + len > l) len = l - begin;
memmove(str + begin, str + begin + len, l - len + 1);
return len;
}
The char range is cut out by moving everything after the range including the terminating `'\0'` to the starting index with `memmove`, thereby overwriting the range. The text in the range is lost.
Note that you need to pass a char buffer whose contents can be changed. Don't pass string literals that are stored in read-only memory.
Problem
I'm trying to figure out how to cut part of a string in C. For example you have this character string "The dog died because a car hit him while it was crossing the road" how would a function go making the sentence "a car hit him while crossing the road" or "a car hit him" How do you go about this with C's library (or/and) a custom function? ok I don't have the main code but this is going to be the structure of this experiment ``` #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <getopt.h> #include "display_usage.c"/*If the user enters wrong arguments it will tell them how it should be */ void cut( const char *file, int option, int first, int last ); int main(int argc, char *argv[] ) { FILE *fp; char ch; fp = fopen("test.txt", "r"); // Open file in Read mode while (ch!=EOF) { ch = fgetc(fp); // Read a Character printf("%c", ch); } fclose(fp); // Close File after Reading return 0; } void cut( const char *file, int reverse, int first, int last ) { return; } ```