You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C#中如何将PHP返回的特定格式数组字符串转换为数组?

Unity中处理PHP返回的特定格式字符串为两个字符串数组

针对你从PHP获取到的["Swww","Sdss"][0,0]格式字符串,可通过C#的字符串处理方法拆分并转换为两个string数组,具体实现如下:

1. 拆分原始字符串为两个数组片段

原始字符串由两个方括号包裹的数组部分直接拼接而成,先定位第一个]的位置,将字符串拆分为两个独立的数组字符串:

string phpResponse = "[\"Swww\",\"Sdss\"][0,0]"; // 从PHP获取的原始字符串
int splitPos = phpResponse.IndexOf(']');
string arrayPart1 = phpResponse.Substring(0, splitPos + 1);
string arrayPart2 = phpResponse.Substring(splitPos + 1);

2. 处理带引号的第一个数组

去除前后方括号,按逗号分割元素,再剥离每个元素的双引号:

using System.Linq; // 需要引入Linq命名空间

string[] result1 = arrayPart1.Trim('[', ']')
                             .Split(',')
                             .Select(item => item.Trim('"'))
                             .ToArray();
// 最终结果:result1 = {"Swww", "Sdss"}

3. 处理数字字符串组成的第二个数组

同样去除前后方括号,直接按逗号分割即可:

string[] result2 = arrayPart2.Trim('[', ']')
                             .Split(',')
                             .ToArray();
// 最终结果:result2 = {"0", "0"}

额外适配场景

如果PHP返回的字符串包含空格(比如["Swww", "Sdss"][0, 0]),可以在拆分后对每个元素做去空格处理:

// 适配带空格的格式
string[] result1 = arrayPart1.Trim('[', ']')
                               .Split(',')
                               .Select(item => item.Trim().Trim('"'))
                               .ToArray();
string[] result2 = arrayPart2.Trim('[', ']')
                               .Split(',')
                               .Select(item => item.Trim())
                               .ToArray();

若需要将第二个数组转为整数数组,可在Select中添加int.Parse()或int.TryParse()完成类型转换。

内容的提问来源于stack exchange,提问作者user19795922

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 01:57:12