string型字符串的替换-strncpy

strncpy有三个参数 第一个参数是要替换的字符串 第二个是源字符串,第三个替换的字符个数

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int main()
{
char ch1[10]="gh";
char ch2[]="abcdef";
strncpy(ch1,ch2,3);
//ch1要替换的字符安串,ch2源字符串,要替换的字符个数
cout<<ch1<<endl;
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 C 语言中,可以使用函数库中的函数来实现字符串替换,例如使用 `strtok()` 函数来分割字符串,使用 `strcpy()` 和 `strcat()` 函数来拷贝和连接字符串。 以下是一个示例代码,用于在字符串替换指定的字符串实例: ```c #include <stdio.h> #include <string.h> void replace(char *str, char *orig, char *rep) { char buffer[100]; char *p; while ((p = strstr(str, orig))) { strncpy(buffer, str, p - str); buffer[p - str] = '\0'; strcat(buffer, rep); strcat(buffer, p + strlen(orig)); strcpy(str, buffer); } } int main() { char str[100] = "hello world! hello world! hello world!"; char orig[] = "world"; char rep[] = "universe"; printf("Before: %s\n", str); replace(str, orig, rep); printf("After: %s\n", str); return 0; } ``` 输出结果如下: ``` Before: hello world! hello world! hello world! After: hello universe! hello universe! hello universe! ``` 在上面的代码中,`replace()` 函数接收三个参数:原始字符串 `str`、要替换字符串 `orig` 和替换字符串 `rep`。该函数使用 `strstr()` 函数找到字符串 `str` 中第一个出现的字符串 `orig` 的位置,然后使用 `strncpy()` 函数将位置之前的字符串复制到缓冲区 `buffer` 中,并在缓冲区中添加替换字符串 `rep`。然后使用 `strcat()` 函数将剩余的字符串添加到缓冲区中,并使用 `strcpy()` 函数将缓冲区中的字符串复制回原始字符串 `str` 中。这样就可以将字符串中所有出现的字符串 `orig` 替换字符串 `rep`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值