用指针实现strrstr函数
时间: 2024-02-22 08:57:19 浏览: 22
strrstr函数是在一个字符串中查找另一个子字符串最后一次出现的位置。下面是用指针实现strrstr函数的代码:
```c
char* strrstr(const char* str, const char* target) {
if (*target == '\0') { // 空字符串
return (char*) str;
}
const char* last = NULL;
while ((str = strstr(str, target)) != NULL) { // 在str中查找target
last = str++; // 记录上一次出现的位置
}
return (char*) last;
}
```
该函数首先判断目标字符串是否为空,如果为空,则直接返回原字符串。然后使用strstr函数在原字符串中查找目标字符串,每次查找到就将上一次出现的位置记录下来,最后返回最后一次出现的位置。注意这里要将const char*转换为char*类型,因为返回的是指向char类型的指针。
相关问题
用指针实现atoi函数
atoi函数是将字符串转换为整数的函数,可以使用指针来实现。以下是一个使用指针实现atoi函数的示例代码:
```c++
#include <iostream>
using namespace std;
int myAtoi(char* str) {
int res = 0;
int sign = 1;
if (*str == '-') {
sign = -1;
str++;
}
while (*str != '\0') {
if (*str >= '0' && *str <= '9') {
res = res * 10 + (*str - '0');
} else {
break;
}
str++;
}
return res * sign;
}
int main() {
char str[] = "-12345";
int num = myAtoi(str);
cout << num << endl;
return 0;
}
```
在这个实现中,我们首先判断字符串的符号,如果是负数,则将符号标记为-1,并将指针向后移动一位。然后,我们遍历字符串中的每个字符,如果是数字,则将其转换为整数并添加到结果中。如果遇到非数字字符,则退出循环。最后,我们将结果乘以符号标记并返回。
用指针实现strcmp函数功能
strcmp函数是用来比较两个字符串是否相等的函数,可以使用指针来实现它的功能。
下面是使用指针实现strcmp函数的代码:
```c
int strcmp(const char *s1, const char *s2) {
while (*s1 && (*s1 == *s2)) {
s1++;
s2++;
}
return *(const unsigned char*)s1 - *(const unsigned char*)s2;
}
```
在这个函数中,我们使用了两个指针s1和s2来比较两个字符串。这两个指针分别指向待比较的两个字符串的首字符。
然后,我们使用一个while循环来遍历这两个字符串,直到遇到字符串的结束符'\0'或者两个字符串中有一个字符不相等为止。
最后,我们返回两个指针指向的字符的差值。这里需要注意的是,我们需要将指针转换成无符号字符指针,以保证比较时不会出现负数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)