c语言string substring,c语言实现SubString,c语言substring

c语言实现SubString,c语言substring

#include

#define N 50

int substring(char *, int, int, char *);

main()

{

int start,len,count;

char s[N];

char t[N];

printf("请输入字符串:\n");

gets(s);

printf("请输入起始位置:");

scanf("%d",&start);

printf("请输入所取字符长度:");

scanf("%d",&len);

count=substring(s,start,len,t);

if(count==-1)

printf("起始值超出范围!\n");

else if(count==-2)

printf("长度超出范围!\n");

else

{

printf("得到的字符串是:");

puts(t);

getch();

}

return 0;

}

int substring(char * s,int start,int len,char * t)

{

int i=0,j=0;

while(s[i])

i++;

if(i

return -1;

else if(i

return -2;

else

{

for(i=start-1;i<=start+len-2;i++)

{

t[j]=s[i];

j++;

}

t[j]='\0';

return 1;

}

}

相关文章暂无相关文章

### C语言中的字符串处理函数 在C语言中,`<string.h>`头文件提供了多种用于处理字符串的标准库函数。这些函数能够执行诸如复制、连接、比较以及搜索等基本操作。 #### 使用 `puts()` 输出带转义字符的字符串 当需要输出带有换行符或其他控制序列的字符串时,可以直接调用`puts()`函数[^1]: ```c #include <stdio.h> int main() { char str1[] = {"China\nBeijing"}; puts(str1); return 0; } ``` 这段代码会先打印“China”,接着在同一行下面打印“Beijing”。 #### 安全地读取用户输入并去除多余的换行符 为了防止潜在的安全风险,推荐使用`fgets()`代替`gets()`来获取用户的键盘输入,并手动移除可能存在的额外换行符[^3]: ```c #include <stdio.h> #include <string.h> #define BUFFER_SIZE 1024 int main(){ char buffer[BUFFER_SIZE]; printf("请输入一段文字:\n"); if (fgets(buffer, sizeof(buffer), stdin)) { size_t length = strlen(buffer); // 如果最后一个字符是'\n'则删除它 if(length > 0 && buffer[length - 1] == '\n'){ buffer[--length] = '\0'; } printf("您输入的内容为:%s\n", buffer); } return 0; } ``` 此程序片段展示了如何利用`fgets()`安全地接收来自标准输入的数据流,并通过简单的逻辑判断去掉不必要的换行符号。 #### 实现自定义的字符串替换功能 对于更复杂的场景比如字符串替换,则可以通过组合多个基础函数来构建自己的解决方案[^5]: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> char* replace_substring(const char *source, const char *oldValue, const char *newValue){ int i, count=0; int oldLen=strlen(oldValue); int newLen=strlen(newValue); // 计算旧子串出现次数 for(i=0; source[i]!= '\0'; ++i){ if(memcmp(source+i, oldValue, oldLen)==0) ++count; } // 创建足够大的目标数组存储最终结果 char *result=(char*)malloc(strlen(source)+count*(newLen-oldLen)+1); memset(result, 0, strlen(source)+count*(newLen-oldLen)+1); char *p=result; while(*source != '\0') { if(memcmp(source, oldValue, oldLen) == 0) { memcpy(p, newValue, newLen); p+=newLen; source += oldLen; }else{ *(p++)=*source++; } } *p='\0'; return result; } // 测试replace_substring函数 void test_replace_function(){ const char *original="hello world"; const char *toFind="world"; const char *replacement="everyone"; char *replacedString=replace_substring(original,toFind,replacement); printf("%s -> %s\n", original, replacedString); free(replacedString); } int main(){ test_replace_function(); return 0; } ``` 上述例子说明了怎样创建一个新的内存区域用来保存修改后的字符串副本,在其中逐步拼接原始部分和新的替代项直到遍历完整个原字符串为止。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值