Android中创建二维字符串数组的代码示例
时间: 2024-05-26 08:09:57 浏览: 9
Sure. Here is an example code for creating a 2D String array in Android:
String[][] myArray = new String[3][2];
myArray[0][0] = "Apple";
myArray[0][1] = "Orange";
myArray[1][0] = "Banana";
myArray[1][1] = "Kiwi";
myArray[2][0] = "Grapes";
myArray[2][1] = "Pineapple";
相关问题
将一维字符串数组用strcpy复制到二维字符串数组
可以使用strcpy函数将一维字符串数组复制到二维字符串数组中。具体步骤如下:
1. 定义一维字符串数组和二维字符串数组,并初始化一维字符串数组。
```c
char str1[] = "hello";
char str2[3][10];
```
2. 使用strcpy函数将一维字符串数组复制到二维字符串数组中。
```c
strcpy(str2[0], str1);
```
这里将一维字符串数组str1复制到了二维字符串数组str2的第一行中。
3. 输出二维字符串数组中的内容。
```c
printf("%s\n", str2[0]);
```
这里输出了二维字符串数组str2的第一行,即复制后的字符串"hello"。
c语言动态创建二维字符串数组
动态创建二维字符串数组可以使用指针数组和malloc函数来实现。以下是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int rows, cols, i, j;
char **arr;
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &cols);
// Allocate memory for pointer array
arr = (char **)malloc(rows * sizeof(char *));
// Allocate memory for each row
for (i = 0; i < rows; i++) {
arr[i] = (char *)malloc(cols * sizeof(char));
}
// Initialize array elements
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
arr[i][j] = 'A' + i + j;
}
}
// Print array elements
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%c ", arr[i][j]);
}
printf("\n");
}
// Free memory
for (i = 0; i < rows; i++) {
free(arr[i]);
}
free(arr);
return 0;
}
```
该程序首先要求用户输入数组的行和列数,然后使用malloc函数分配指针数组和每行的内存空间。接下来,它初始化数组元素并打印它们。最后,程序释放动态分配的内存。
在上面的示例代码中,我们使用了char类型的二维数组,但此方法也可以用于其他类型的二维数组。