I'm trying to check if any string entered after a certain message I do have a working version in SQL that I want to use almost the same one in C#
Usage in SQL:
ELSE IF #Msg LIKE '/Message %'
Usage in C#:
else if (Msg == "/Message ")
I want the tool to check if any string entered right after /Message.
Thanks in advance :)
You can use the following string functions:
var Msg = "A message to check";
For LIKE 'SomeText%':
if (Msg.StartsWith("SomeText"))
For LIKE '%SomeText':
if (Msg.EndsWith("SomeText"))
For LIKE '%SomeText%':
if (Msg.Contains("SomeText"))
Here is how the TSQL LIKE keyword works.
using System;
namespace SqlLike
{
class Program
{
static void Main(string[] args)
{
var findMe = "ABCHelloXYZ";
// LIKE '......%'
if (findMe.StartsWith("ABC"))
{
Console.WriteLine("Yay");
}
// LIKE '%......'
if (findMe.EndsWith("XYZ"))
{
Console.WriteLine("Woohoo");
}
// LIKE '%......%'
if (findMe.Contains("Hello"))
{
Console.WriteLine("JackPot!!");
}
Console.ReadLine();
}
}
}
Your requirements are a little vague, but this should get you there (with a little adjustment as needed).
String Msg = "/Message somethingelse";
if (Msg.Contains("/Message ") && (Msg.Length > 9) )
{
String str = Msg.Substring(9);
Console.Write("str: " + str);
}
As #Scott suggested you can also use:
if (Msg.StartsWith("/Message ") && (Msg.Length > 9))
{
String str = Msg.Substring(9);
Console.Write("str: " + str);
}
Related
I want to ask you regarding for the searching in C# and why there is a Not Found statement if already found the answer or the data itself.
Here is the code:
Console.WriteLine("Enter Plate Number: ");
string plateNumber1 = Console.ReadLine();
var searchPlateNumberDAL = new ParkingSystemDAL(_iconfiguration);
var listSlotParking = searchPlateNumberDAL.GetList();
listSlotParking.ForEach(item =>
{
bool searchItem = item.plateNumber == plateNumber1;
if (searchItem == true)
{
Console.WriteLine(item.parkingId);
}
else
{
Console.WriteLine("Not Found");
}
});
output
I think there some garbage value is present.
So, code will be
if(item.plateNumber.ToString().Trim().ToUpper() == plateNumber1.ToString().Trim().ToUpper())
{
Console.WriteLine(item.parkingId);
}
you can also use Linq Where expression instead of ForEach
if( listSlotParking.Where(x =>x.planteNumberplateNumber.ToString().Trim().ToUpper() == plateNumber1.ToString().Trim().ToUpper()).ToList().Count()>0)
{
Console.WriteLine(item.parkingId);
}
Try
item.plateNumber.Trim() == plateNumber1.Trim()
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 :TwitchUser1234#TwitchUser1234.tmi.twitch.tv 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.");
}
}
}
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"]);
...
String has a method Contains(string) that does the job:
if (ChantInputs.Contains("bits")
{
print("I made it here.");
}
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();
}
}
}
I'm creating a command system for my application but i don't know how to make c# recognize a pattern in my string.
Example:
add(variable1, variable2)
How to make c# recognize addUser(...) and do some stuff?
I'm currently using string contains but if user type add()()()()() or add((((((, it still work!
Please help!
sorry about my english!
This may not be perfect, but might give you some ideas :)
static void Main(string[] args)
{
string example_input = "xxxxx Add(user1, user2) xxxxxx";
string myArgs = getBetween2(example_input, "Add(", ")"); //myArgs = "user1, user2"
if (myArgs != "EMPTY")
{
myArgs = myArgs.Replace(" ", ""); // remove spaces... myArgs = "user1,user2"
string[] userArray = myArgs.Split(',');
foreach (string user in userArray)
{
Console.WriteLine(user);
//Your code here
}
}
Console.ReadKey(); //pause
}
static string getBetween2(string strSource, string strStart, string strEnd)
{
try
{
int Start, End;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
else
{
return "EMPTY";
}
}
catch
{
return "EMPTY";
}
}
Is there a way to do this in C# without making a new method to overload for every var type there is?
$box = !empty($toy) : $toy ? "";
The only ways I can think of to do it is either:
if (toy != null)
{
box += toy;
}
or this:
public string emptyFilter(string s) ...
public int emptyFilter(int i) ...
public bool emptyFilter(bool b) ...
public object emptyFilter(object o)
{
try
{
if (o != null)
{
return o.ToString();
}
else
{
return "";
}
}
catch (Exception ex)
{
return "exception thrown":
}
}
box += this.emptyFilter(toy);
I basically wanna check to make sure that the variable/property is set/not empty/exists/has value/etc... and return it or "" without some ridiculous about of code like above.
You could use the conditional operator (?:):
string box = (toy != null) ? toy.ToString() : "";
return variable ?? default_value;
That what you're going for? I'm a little confused considering you're showing PHP code and tag this with C#.
There's also the Nullable<T> type you can use.
How bout an extender class?
public static class ToStringExtender
{
public static String ToStringExt(this Object myObj)
{
return myObj != null ? myObj.ToString() : String.Empty;
}
}
var myobject = foo.ToStringExt()
DEMO
I'm not sure of what he wants, BUT:
string str = String.Empty;
str += true;
str += 5;
str += new object();
str += null;
This is perfectly legal. For each one adition the ToString() will be called. For null, simply nothing will be added.
The value of str at the end: True5System.Object
or,
var s = (toy?? "").ToString();
or
var s = (toy?? string.Empty).ToString();
i think there may be a slight misunderstanding about how var is used; but that's a separate topic.
maybe this below will help:
box += (toy ?? "").ToString();
I am trying to convert this code from C# to VB. Tried to use third party tools, but not successful. Can some one help me .Thanks
private static string RemoveInvalidHtmlTags(this string text)
{
return HtmlTagExpression.Replace(text, new MatchEvaluator((Match m) =>
{
if (!ValidHtmlTags.ContainsKey(m.Groups["tag"].Value))
return String.Empty;
string generatedTag = String.Empty;
System.Text.RegularExpressions.Group tagStart = m.Groups["tag_start"];
System.Text.RegularExpressions.Group tagEnd = m.Groups["tag_end"];
System.Text.RegularExpressions.Group tag = m.Groups["tag"];
System.Text.RegularExpressions.Group tagAttributes = m.Groups["attr"];
generatedTag += (tagStart.Success ? tagStart.Value : "<");
generatedTag += tag.Value;
foreach (Capture attr in tagAttributes.Captures)
{
int indexOfEquals = attr.Value.IndexOf('=');
// don't proceed any futurer if there is no equal sign or just an equal sign
if (indexOfEquals < 1)
continue;
string attrName = attr.Value.Substring(0, indexOfEquals);
// check to see if the attribute name is allowed and write attribute if it is
if (ValidHtmlTags[tag.Value].Contains(attrName))
generatedTag += " " + attr.Value;
}
// add nofollow to all hyperlinks
//if (tagStart.Success && tagStart.Value == "<" && tag.Value.Equals("a", StringComparison.OrdinalIgnoreCase))
// generatedTag += " rel=\"nofollow\"";
if (tag.Value.ToString() == "object")
{
generatedTag += (tagEnd.Success ? " height=\"374\" width=\"416\"" + tagEnd.Value : ">");
}
else
{
generatedTag += (tagEnd.Success ? tagEnd.Value : ">");
}
return generatedTag;
}));
}
The problem converting this code is that you have a lambda expression with a multi-line statement body:
(Match m) =>
{
...a lot of code
}
Since VB9 doesn't support this, you'll want to put the code in brackets into its own function instead:
Private Function GetValue(m As Match) As String
....a lot of code
End Function
Then your RemoveInvalidHtmlTags code will look like this:
Return HtmlTagExpression.Replace(text, new MatchEvaluator(AddressOf GetValue))
You can use free tools to translate the rest of the code.
Have you tried this free tool?