我正在尝试找出如何在C中剪切字符串的一部分。例如,您有以下字符串:“狗死了,因为汽车在横过马路时撞到了他”该函数将如何使句子“ a或“有车撞到他”
您如何使用C的库(或/和)自定义函数进行操作?
好的,我没有主要代码,但这将是本实验的结构
#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;
}
以下函数从char缓冲区中切出给定范围。该范围由起始索引和长度标识。可以指定一个负长度,以指示从字符串的起始索引到结尾的范围。
/*
* 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;
}
通过将范围内的所有内容(包括终止符)都移动'\0'
到,可以切出char范围memmove
,从而覆盖范围。范围内的文本丢失。
请注意,您需要传递一个可以更改其内容的char缓冲区。不要传递存储在只读存储器中的字符串文字。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句