利用指针把字符串中的"you"全部换成"me"
时间: 2023-05-14 18:06:49 浏览: 38
可以使用以下代码实现:
```c
#include <stdio.h>
#include <string.h>
void replace(char *str, const char *old, const char *new) {
char *pos, temp[1000];
int index = 0;
int old_len = strlen(old);
while ((pos = strstr(str, old)) != NULL) {
strcpy(temp, str);
index = pos - str;
str[index] = '\0';
strcat(str, new);
strcat(str, temp + index + old_len);
}
}
int main() {
char str[1000] = "I love you, you love me, we're a happy family.";
replace(str, "you", "me");
printf("%s\n", str);
return 0;
}
```
输出结果为:
```
I love me, me love me, we're a happy family.
```
相关问题
利用指针删除字符串中的数字
可以使用指针遍历字符串,找到其中的数字并删除。以下是一个 C++ 的示例代码:
```cpp
#include <iostream>
using namespace std;
void removeDigits(char* str) {
char* p = str; // 定义指针 p 指向 str 的起始位置
while (*p) { // 当指针 p 指向的字符不为 '\0' 时循环
if (isdigit(*p)) { // 如果当前字符是数字
char* q = p; // 定义指针 q 指向当前位置
while (*q) { // 从当前位置开始往后遍历
*q = *(q + 1); // 将后面的字符向前移动一位
q++;
}
continue; // 继续从当前位置检查下一个字符
}
p++; // 如果当前字符不是数字,则指针 p 向后移动一位
}
}
int main() {
char str[] = "abc123def456";
removeDigits(str);
cout << str << endl; // 输出结果为 "abcdef"
return 0;
}
```
上述代码中,`removeDigits` 函数接受一个字符指针 `str`,并在原地删除其中的数字。指针 `p` 指向 `str` 的起始位置,循环遍历字符串中的每个字符。如果当前字符是数字,则使用指针 `q` 从当前位置开始往后遍历,将后面的字符向前移动一位。如果当前字符不是数字,则指针 `p` 向后移动一位。最终,字符串中的所有数字都被删除了。
设计一个函数利用指针删除字符串中的数字
可以设计一个函数,接收一个指向字符串的指针,然后遍历整个字符串,如果当前字符是数字,则将其删除,具体实现如下:
```c++
void deleteDigits(char* str) {
char* p = str; // 定义一个指针,指向字符串的开头
while (*p != '\0') { // 遍历整个字符串
if (*p >= '0' && *p <= '9') { // 如果当前字符是数字
char* q = p; // 定义一个指针,指向当前位置
while (*q != '\0') { // 从当前位置开始,将后面的字符向前移动
*q = *(q + 1);
q++;
}
} else {
p++; // 如果当前字符不是数字,则继续向后遍历
}
}
}
```
需要注意的是,由于字符串的长度是不变的,因此在删除一个数字后,后面的字符需要向前移动,以保证字符串的完整性。