c++指针法对字符串
时间: 2023-12-05 12:39:26 浏览: 38
C++中可以使用指针来操作字符串。以下是一些常见的指针操作字符串的方法:
1. 使用指针遍历字符串并输出每个字符:
```c++
char str[] = "hello";
char *p = str;
while (*p != '\0') {
cout << *p;
p++;
}
// 输出:hello
```
2. 使用指针获取字符串的长度:
```c++
char str[] = "hello";
char *p = str;
int len = 0;
while (*p != '\0') {
len++;
p++;
}
cout << len; // 输出:5
```
3. 使用指针比较两个字符串是否相等:
```c++
char str1[] = "hello";
char str2[] = "world";
char *p1 = str1;
char *p2 = str2;
while (*p1 == *p2 && *p1 != '\0' && *p2 != '\0') {
p1++;
p2++;
}
if (*p1 == '\0' && *p2 == '\0') {
cout << "str1 equals str2";
} else {
cout << "str1 does not equal str2";
}
```
4. 使用指针连接两个字符串:
```c++
char str1[] = "hello";
char str2[] = "world";
char *p1 = str1;
while (*p1 != '\0') {
p1++;
}
char *p2 = str2;
while (*p2 != '\0') {
*p1 = *p2;
p1++;
p2++;
}
*p1 = '\0';
cout << str1; // 输出:helloworld
```