Home > Enterprise >  How do I parse and find a string in a C# script?
How do I parse and find a string in a C# script?

Time:10-23

I've been trying to parse and search for a specific word in a big string, but I can't seem to be able to figure it out. I have created a script that connects a Twitch Channel's chat into unity.

An example of a message would be:

"@badge-info=subscriber/4;badges=moderator/1,subscriber/3,bits/1;bits=1;color=;display-name=TwitchUser1234;emotes=;flags=;id=da6ec4c6-af61-4346-abc-123456789;mod=1;room-id=12345678;subscriber=1;tmi-sent-ts=160987654321;turbo=0;user-id=123456789;user-type=mod :[email protected] PRIVMSG #thechannelyouarewatching :PogChamp1 Another Test Bit"

I tried parsing and searching for the string 'bits' the message by doing:

 private void GameInputs(string ChatInputs)
 {
    string Search;
    Search = ChatInputs.Split(";", "=");
    if(string "bits" in Search)
    {
        print("I made it here.");
    }
}

I'm at a complete loss and have no idea how to do this. Any help is appreciated.

If my full code is needed it is:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.ComponentModel;
using System.Net.Sockets;
using System.IO;

public class TwitchChat : MonoBehaviour
{

    private TcpClient twitchClient;
    private StreamReader reader;
    private StreamWriter writer;

    public string username, password, channelName; // http://twitchapps.com/tmi

    // Start is called before the first frame update
    void Start()
    {
        Connect();
    }

    void Update()
    {
        if(!twitchClient.Connected)
        {
            Connect();
        }

        ReadChat();
    }

    private void Connect()
    {
        twitchClient = new TcpClient("irc.chat.twitch.tv", 6667);
        reader = new StreamReader(twitchClient.GetStream());
        writer = new StreamWriter(twitchClient.GetStream());

        writer.WriteLine("PASS "   password);
        writer.WriteLine("NICK "   username);
        writer.WriteLine("USER "   username   " 8 * :"   username);
        writer.WriteLine("JOIN #"   channelName);
        writer.WriteLine("CAP REQ :twitch.tv/tags");
        writer.Flush();
    }

    private void ReadChat()
    {
        if (twitchClient.Available > 0)
        {
            var message = reader.ReadLine();

            print(message);

            GameInputs(message);
        }
    }

    private void GameInputs(string ChatInputs)
    {
        string Search;
        Search = ChatInputs.Split(";", "=");
        if(string "bits" in Search)
        {
            print("I made it here.");
        }
    }
}

CodePudding user response:

If you want to pull the value of "bits=xx" out, this would do it:

var b = value.Split(';').FirstOrDefault(s => s.StartsWith("bits="))?[5..];

b will be null if "bits=" is not present

If you're going to parse a lot of values out of this string consider turning it into a dictionary:

var c = new []{'='};

var d = value.Split(';').ToDictionary(s => s.Split(c,2)[0], s => s.Split(c,2)[1]);

It's slightly inefficient to split twice, if it bothers you, you can sub string:

value.Split(';').ToDictionary(s => s[..s.IndexOf('=')], s => s[s.IndexOf('=') 1..]);

This gives a dictionary of string, so you can do like:

if(d.ContainsKey("bits")){
  var bits = int.Parse(d["bits"]);
  ...

CodePudding user response:

String has a method Contains(string) that does the job:

if (ChantInputs.Contains("bits")
{
     print("I made it here.");
}

CodePudding user response:

You can try below.

private void GameInputs(string ChatInputs)
{
string[] Search = ChatInputs.Split(new char[] { ';', '=' });
foreach(string s in Search)
 {
  if(s == "bits")
  {
    print("I made it here.");
  }
 }
}  

Below is the working code.

using System;

namespace ConsoleApp3
{
class Program
{
    static void Main(string[] args)
    {
        string str = "one;two;test;three;test test";

        string[] strs = str.Split(new char[] { ';', ' ' });

        foreach(string s in strs)
        {
            if(s == "test")
            {
                Console.WriteLine(s);
            }
        }

        Console.ReadLine();
    }
}
}
  • Related