不使用strcpy 函数用指针把s1复制到s2中
时间: 2023-05-18 07:04:06 浏览: 52
可以使用指针遍历s1和s2,逐个将s1中的字符赋值给s2,直到遇到'\0'为止。以下是示例代码:
```
void copyString(char *s1, char *s2) {
while (*s1 != '\0') {
*s2 = *s1;
s1++;
s2++;
}
*s2 = '\0';
}
```
调用方式为:
```
char s1[] = "Hello, world!";
char s2[20];
copyString(s1, s2);
printf("%s", s2);
```
输出结果为:
```
Hello, world!
```
相关问题
C++函数用s2替换str中的s1,函数返回替换后的字符串的指针。
可以使用C++的string类来进行字符串的替换操作,具体实现可以参考如下的代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
char* replaceString(string str, string s1, string s2)
{
size_t pos = 0;
while ((pos = str.find(s1, pos)) != string::npos)
{
str.replace(pos, s1.length(), s2);
pos += s2.length();
}
char* result = new char[str.length() + 1];
strcpy(result, str.c_str());
return result;
}
int main()
{
string str = "hello world, hello c++!";
string s1 = "hello";
string s2 = "hi";
char* result = replaceString(str, s1, s2);
cout << result << endl;
delete[] result;
return 0;
}
```
在这个代码中,replaceString函数接收三个参数:原字符串str,需要替换的字符串s1和替换后的字符串s2。函数使用string类的find和replace函数来进行字符串的替换操作,并最终以字符数组的形式返回替换后的字符串指针。需要注意的是,由于返回的指针指向的是动态分配的内存,所以在使用完毕后需要手动释放内存,避免内存泄漏。
用s2替换str中的s1,s1和s2都是字符串,长度可能不相等,用指针的方法
好的,如果您想用指针的方法来实现字符串替换,可以使用 C 风格字符串的指针和循环结合起来实现。具体步骤如下:
1. 包含头文件 #include <cstring>
2. 创建一个字符串,存储待替换的字符串。
```
char str[] = "this is a test string";
char s1[] = "test";
char s2[] = "replace";
```
3. 使用 strstr 函数查找 s1 的位置。
```
char* pos = strstr(str, s1);
```
如果 s1 存在于 str 中,pos 就是 s1 在 str 中的位置;否则 pos 就是 NULL。
4. 使用循环和 strcpy 函数来实现替换。
```
while (pos != NULL) {
strcpy(pos, s2);
pos = strstr(pos + strlen(s2), s1);
}
```
以上代码的含义是:如果 s1 存在于 str 中,则从字符串的 pos 位置开始,使用 strcpy 函数将 s2 替换为 s1。并更新 pos 的值为下一个 s1 出现的位置。
5. 最终得到的字符串即为替换后的结果。
```
cout << str << endl;
```
输出结果为:"this is a replace string" 中的 "test" 被替换为了 "replace"。
希望这些步骤能够帮助您进行字符串替换。