定义一个长度为5的字符串数组,并初始化其初值为“open”, “door”, “the”, “open”, “name”;计算该数组中 “open”出现的次数,并倒序输出数组元素使用Java实现
时间: 2023-10-19 17:07:27 浏览: 109
下面是对应的Java代码实现:
```java
public class Main {
public static void main(String[] args) {
String[] arr = {"open", "door", "the", "open", "name"};
int count = 0;
for (String s : arr) {
if (s.equals("open")) {
count++;
}
}
System.out.println("open 出现的次数为:" + count);
// 倒序输出数组元素
for (int i = arr.length - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}
```
输出结果为:
```
open 出现的次数为:2
name open the door open
```
相关问题
定义一个长度为5的字符串数组,并初始化其初值为“open”, “door”, “the”, “open”, “name”;计算该数组中 “open”出现的次数,并倒序输出数组元素
下面是对应的Python代码实现:
```python
arr = ["open", "door", "the", "open", "name"]
count = arr.count("open") # 计算 "open" 出现的次数
print("open 出现的次数为:", count)
arr.reverse() # 倒序输出数组元素
print("倒序输出数组元素为:", arr)
```
输出结果为:
```
open 出现的次数为: 2
倒序输出数组元素为: ['name', 'open', 'the', 'door', 'open']
```
使用字符串变量定义一个数组并初始化
好的,你可以这样使用字符串变量来定义一个字符数组并初始化:
```
char str[] = "Hello, world!";
char myArray[sizeof(str)] = {0};
for (int i = 0; i < sizeof(str); i++) {
myArray[i] = str[i];
}
```
这里首先定义了一个名为 `str` 的字符串变量,并将其初始化为 `"Hello, world!"`。然后定义了一个名为 `myArray` 的字符数组,并手动指定其大小为 `sizeof(str)`,即字符串变量 `str` 中字符的总数。数组中的所有元素在定义时都被初始化为零。
接下来使用一个循环遍历字符串变量 `str` 的所有字符,并将其逐一拷贝到字符数组 `myArray` 中。这样就完成了字符数组的初始化。