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

如何让C#代码读取到第一个双引号后停止并正确提取游戏名称?

问题与解决方法

问题背景

给定Games输入示例:

Games input is ["gameextrainfo":"Potion Craft: Alchemist Simulator","gameid":"1210320","]

初始C#代码尝试提取游戏名称,但无法满足需求:

using System;
public class CPHInline
{
    public bool Execute()
    {
        String str = args["Games"].ToString();
        string result = str.Substring(17);
        CPH.SendMessage(result, true);
        return true;
    }
}

需求是输出格式为 The Game is [游戏名称],即准确提取如Potion Craft: Alchemist Simulator的游戏名称,且不包含名称后的双引号。

修改后的代码仅输出游戏名称的第一个字母:

using System;

public class CPHInline
{
    public bool Execute()
    {
        
        String str = args["Games"].ToString();
        String result = str.Contains("\"") ?  str.Substring(17, str.IndexOf("\"")): str;
        CPH.SendMessage(result, true);
        return true;
        
        return true;
    }
}

错误原因

  1. Substring参数理解错误:Substring(int startIndex, int length)的第二个参数是截取的长度,不是结束索引。
  2. 双引号定位错误:str.IndexOf("\"")返回的是字符串最开头的双引号位置(索引很小,比如1),用这个值作为截取长度,只会从索引17开始取1个字符,所以只输出单个字符。

正确代码实现

方法一:精准定位起始与结束位置

using System;

public class CPHInline
{
    public bool Execute()
    {
        string str = args["Games"].ToString();
        // 定位游戏名称的起始点:跳过"gameextrainfo":"这段内容
        int startPos = str.IndexOf("gameextrainfo\":\"") + "gameextrainfo\":\"".Length;
        // 找到起始点之后的第一个双引号(游戏名称的结束位置)
        int endPos = str.IndexOf("\"", startPos);
        // 截取游戏名称
        string gameName = str.Substring(startPos, endPos - startPos);
        // 按要求格式发送消息
        CPH.SendMessage($"The Game is {gameName}", true);
        return true;
    }
}

方法二:分步截取简化逻辑

using System;

public class CPHInline
{
    public bool Execute()
    {
        string str = args["Games"].ToString();
        // 先截取从"gameextrainfo":"之后的所有内容
        string tempStr = str.Substring(str.IndexOf("gameextrainfo\":\"") + "gameextrainfo\":\"".Length);
        // 再截取到第一个双引号之前的部分,就是游戏名称
        string gameName = tempStr.Substring(0, tempStr.IndexOf("\""));
        CPH.SendMessage($"The Game is {gameName}", true);
        return true;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 07:03:17