如何将原本是数组的字符串存入本地存储后,将其取出后转为原来的数组
时间: 2023-12-03 18:42:42 浏览: 41
我们可以使用 JSON.stringify() 方法将数组转换为字符串进行存储,然后使用 JSON.parse() 方法将字符串转换回数组。
示例代码如下:
```javascript
// 原始数组
var arr = [1, 2, 3];
// 将数组转换为字符串并存储到本地存储中
localStorage.setItem('myArr', JSON.stringify(arr));
// 从本地存储中取出字符串并将其转换为数组
var storedArr = JSON.parse(localStorage.getItem('myArr'));
console.log(storedArr); // 输出 [1, 2, 3]
```
在这个例子中,我们使用了 localStorage 对象来存储字符串。您也可以使用 sessionStorage 或其他存储方式来存储字符串。
相关问题
将取出的字符串存入数组
在 C 语言中,我们可以使用字符数组和字符串函数将取出的字符串存入数组中。具体操作如下:
```
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello world! How are you?";
char *token;
char arr[10][20]; // 定义一个二维字符数组,用于存储取出的字符串
int i = 0;
// 将字符串分解为若干个子字符串
token = strtok(str, " ");
// 循环取出子字符串并存入数组中
while (token != NULL) {
strcpy(arr[i], token); // 将子字符串复制到数组中
token = strtok(NULL, " "); // 取出下一个子字符串
i++; // 数组下标加一
}
// 输出存入数组中的字符串
for (int j = 0; j < i; j++) {
printf("%s\n", arr[j]);
}
return 0;
}
```
在上面的代码中,我们首先定义了一个字符串 `str`,用于存储要取出的字符串。然后,我们定义了一个二维字符数组 `arr`,用于存储取出的字符串。接着,我们使用 `strtok()` 函数将字符串分解为若干个子字符串,并循环取出子字符串并存入数组中。最后,我们使用 `printf()` 函数输出存入数组中的字符串。
需要注意的是,在存入数组中的字符串长度不能超过数组的大小,否则可能会发生内存溢出等错误。在上面的代码中,我们定义了 `arr` 为一个大小为 10x20 的二维字符数组,可以存储最多 10 个长度不超过 20 的字符串。
将字符串其数组中的字符串存入TreeMap JAVA
可以通过以下步骤将一个字符串数组中的字符串存入 TreeMap 中:
1. 创建一个 TreeMap 对象,用于存储字符串。
```
TreeMap<String, String> treeMap = new TreeMap<>();
```
2. 遍历字符串数组,将每个字符串作为 key,value 可以为空字符串。
```
for (String str : strArray) {
treeMap.put(str, "");
}
```
完整代码如下:
```
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
String[] strArray = {"apple", "banana", "orange", "pear"};
TreeMap<String, String> treeMap = new TreeMap<>();
for (String str : strArray) {
treeMap.put(str, "");
}
System.out.println(treeMap);
}
}
```
输出结果为:
```
{apple=, banana=, orange=, pear=}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)