用C++写一个模拟strstr函数的int型新函数,不能用指针,若找到返回1-n,否则返回0
时间: 2023-06-14 10:05:50 浏览: 50
以下是使用C++实现模拟strstr函数的代码,注意不能使用指针:
```c++
int my_strstr(char s[], char t[]) {
int slen = strlen(s);
int tlen = strlen(t);
for (int i = 0; i <= slen - tlen; i++) {
int j = 0;
while (j < tlen && s[i + j] == t[j]) {
j++;
}
if (j == tlen) {
return i + 1;
}
}
return 0;
}
```
该函数接受两个字符串作为参数,依次遍历字符串s中所有可能的起始位置,并尝试将s中以该位置为起点的子串与t进行匹配。如果匹配成功,则返回该子串在s中的起始位置加1,否则返回0。
相关问题
c++编写一个函数: char *ReplaceString(char * str, char * s1, char * s2); 该函数用s2替换str中的s1,函数返回替换后的字符串的指针。
以下是实现该函数的代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
char *ReplaceString(char * str, char * s1, char * s2){
int len1 = strlen(s1);
int len2 = strlen(s2);
char *p = strstr(str, s1);
if(p == NULL){ // 如果找不到s1,则直接返回原字符串
return str;
}
int len = strlen(str) - len1 + len2;
char *newStr = new char[len+1];
memset(newStr, 0, len+1);
strncpy(newStr, str, p-str); // 复制s1前面的字符串
strcat(newStr, s2); // 连接s2
strcat(newStr, p+len1); // 连接s1后面的字符串
return newStr;
}
int main(){
char str[] = "Hello, world!";
char s1[] = "world";
char s2[] = "C++";
char *newStr = ReplaceString(str, s1, s2);
cout << newStr << endl;
delete[] newStr;
return 0;
}
```
该函数使用了 strstr 函数来查找 s1 是否在 str 中出现,如果找到了,则使用 strncpy、strcat 等函数来构造新的字符串,并返回新字符串的指针。如果找不到 s1,则直接返回原字符串。注意,该函数返回的新字符串是在堆上动态分配的,使用完后需要手动释放。
请用c++写一个字符串分割函数
下面是一个使用 C 语言写的字符串分割函数的示例:
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// 定义一个结构体用于表示分割后的子串
typedef struct {
char *str; // 子串的内容
int len; // 子串的长度
} substring;
// 定义一个函数用于分割字符串
// 参数 str 指向需要分割的字符串,参数 delim 指向分隔符字符串,参数 substrings 指向分割后的子串数组
// 函数返回分割后的子串数量
int split_string(char *str, char *delim, substring *substrings) {
// 定义一个指针变量 p 指向当前位置
char *p = str;
// 定义一个计数器 count 用于记录分割后的子串数量
int count = 0;
// 使用循环不断地分割字符串
while (1) {
// 在字符串中查找下一个分隔符
char *q = strstr(p, delim);
// 如果分隔符不存在,则表示已经分割完成
if (q == NULL) {
// 将剩余的字符串作为最后一个子串
substrings[count].str = p;
substrings[count].len = strlen(p);
// 返回子串数量
return count + 1;
}
// 否则将当前子串的内容和长度记录到数组中
substrings[count].str = p;
substrings[count].len = q - p;
// 将指针 p 移动到下一个子串的开头
p = q + strlen(delim);
// 增加子串计数器
count++;