c++替换字符数组的2个相连的元素
时间: 2023-05-16 17:06:03 浏览: 92
可以使用一个临时变量来交换这两个元素的值,例如:
```c
char arr[] = "hello";
int index = 2;
char temp = arr[index];
arr[index] = arr[index+1];
arr[index+1] = temp;
```
这样就可以将字符数组中下标为2和下标为3的两个元素交换位置了。
相关问题
c++替换字符数组的某一位置
可以使用数组下标的方式来替换字符数组的某一位置,例如:
```c
char str[] = "hello world";
str[6] = 'C';
printf("%s", str); // 输出结果为 "hello Corld"
```
这样就可以将字符数组中下标为6的位置的字符替换为'C'。
C++遍历求字符数组的元素个数
可以使用 strlen 函数来求字符数组的元素个数,具体代码如下:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello World!";
int len = strlen(str);
printf("字符数组的元素个数为:%d\n", len);
return 0;
}
输出结果为:
字符数组的元素个数为:12