C# read and react to a text string - c#

assume that there is a string named "message", and assume an user type in the console,
"!My FB List", but words "FB" and "List" could be change. But "!My" won't change. So, I want to save the text the user type. Only if user used "!My" before the other words.
So, I don't know how to get this to 'if' command. Plz help me.
if (message == "!My "

Do you mean something like this?
if (message.StartsWith("!My "))
{
// do something
}
This code works in most situations. However, if you need to resolve situations like Kshitij Mehta mentioned in the comments, you'd be probably better off with a Split method parsing the string and comparing the first object of the array to the required string.
When you've split the input string into an array, you will just compare strings in a typical fashion (==), probably no need for fancy methods in that scenario.
One more "however" to consider - if your input string is long, splitting might not be the best idea to do. In that case I'd probably use regular expressions to compare the beginning of the inputted string.
The implementation depends on your needs. Just pick what suits you the best :)

It sounds like you want to accept commands and then do specific things based on those commands. Apparently, the "command" is the first word in the text typed by the user.
Thus, I'd split the message at whitespace and then switch for the first word:
var words = message.Split();
var command = words[0];
switch (command) {
case "!My":
// Do something
...
break;
case "!SomethingElse":
// Do something else
...
break;
...
}
Afterwards, you can use words[1] to get "FB" and words[2] to get "list". Be sure to use words.Length to verify if the required number of parameters has been specified before trying to access them.

String class includes many static methods, among which is StartsWith().
so your if statement can simply be
if(UserString.StartsWith("!My"))
{
// other conditional code here
}
It is not clear from your question whether you want to include cases where the user types "!My" before typing anything else, but he/she does NOT type a space immediately after typing !My.
If you only want to process the code if the three characters "!My" were followed by a space, then, (as suggested by #Walther), add a space to the test string in the StartsWith() method
if(UserString.StartsWith("!My "))
{
// other conditional code here
}

Related

How to find and prioritize words from a given Enum list?

I have an ENUM defined as follows:
public enum TextType {
JOIN,
SUBSCRIBE,
STOP,
HELP,
CANCEL,
UNSUBSCRIBE,
UPGRADE,
BALANCE,
USAGE
}
I would like to prioritize this and filter it as follows:
Yes (if phone is not yet verified to receive text then accept this text; else ignore and go to the next one)
stop, cancel, unsubscribe
Help
Balance or USAGE
UPGRADE
So basically when the User sends a Text say "YES BALANCE" then internally first I do a check to see if the phone number
is registered. If registered then I should use the text "Balance" and return the balance. But if the phone us unregistered
then I should use the text "YES" to register the phone first and ignore the rest.
My issue is currently I am using the Enum.IsDefined to find out if the above is a valid Text and since we have two
different texts combined it fails right away.
if (Enum.IsDefined(typeof(TextType), VtextType))
So how do I rewrite the below IF condition in C# so that I am able to accept both 'Yes' and 'Balance'. Should I change the definition of my Enum or should I use "contains" or should I use regex? I am using .Net4.5
Please help.
After Michaels reply can I loop through the string of array as:
foreach (string s in Tokens)
{
Console.WriteLine(s);
}
Will this work?
It sounds like you are receiving a plain text message that you need to parse for a set of instructions. Once you've parsed the instructions, you can then traverse a representative data structure such as an array or abstract syntax tree and make decisions.
Without knowing the full syntax of the messages you're receiving, I can only guess at the best way to parse them. Some options are:
Split the message by whitespace into an array of tokens and loop through the tokens
Use a more sophisticated grammar parsing library such as Irony
Enums may come in handy when defining the set of tokens you're able to parse.
Update: If you're just looking to split up the string and look at each word (or token), you can use something like:
var Tokens = Regex.Split(myString, #"\s+");
Now you have an array of strings, and you can look at each string in the array individually. You could see if the first string is "YES", try to parse each string as your Enum, etc.

Parsing Log using something else than string split c#

I'm pretty sure it has been asked before, but I could not find anything good.
I'm trying to parse a log but having troubles with it.
At first it looked pretty easy because the log is build like this:
thing,thing,thing,thing
so I string split it on the ,
however in the value itself it is possible that a , appears, and this is where I did not know what to do anymore.
How would I successfully parse this kind of log?
Edit~~
here is an log example:
1326139200953,info,,0,"str value which may contain, ",,,0
1326139201109,info,,0,"str value which may contain, ",,,0
1326139201265,info,,0,"str value which may contain, ",,,0
1326139201999,start,,0,,,,0
1326139368296,new,F:\Dir\Dir\file.txt,1536,,0,,0
``
If your log file doesn't have field encapsulators, the fields have variable width, and the separator/delimiter can also appear in a field, then it's likely you can't program something that will work in all cases.
Can you supply an example of your log file data? It may be possible to match the parts you need with a regex.
Unfortunately I think your question is not answerable in its current state, please provide more info.
Edit: Thanks for updating the question, you do have field encapsulators (double quotes). This will make it easier!
I think there are many ways to do this. Personally i think i would carry on splitting on commas, but then loop over the resulting array, checking if the first character of any value is a double quote. If it is, then you need to join it to the array item after it. If the last character of the joined array item isn't a double quote, you need to continue joining until you've closed your opening double quote.
There's certainly a better way so you may wish to wait for another solution.
Edit 2: Give this a go and let me know how you get on:
string myRegex = #"(?<=^(?:[^""]*""[^""]*"")*[^""]*),";
string[] outputArray = Regex.Split(myStr, myRegex);

What's the best way to parse a string for "bad" words in C#?

I'm thinking of something like:
foreach (var word in paragraph.split(' ')) {
if (badWordArray.Contains(word) {
// do something about it
}
}
but I'm sure there's a better way.
Thanks in advance!
UPDATE
I'm not looking to remove obscenities automatically... for my web app, I want to be notified if a word I deem "bad" is used. Then I'll review it myself to make sure it's legit. An auto flagging system of sorts.
While your way works, it may be a bit time consuming. There is a wonderful response here for a previous SO question. Though the question talks about PHP instead of C#, I think it can be easily ported.
Edit to add sample code:
public string FilterWords(string inputWords) {
Regex wordFilter = new Regex("(puppies|kittens|dolphins|crabs)");
return wordFilter.Replace(inputWords, "<3");
}
That should work for you, more or less.
Edit to answer OP clarification:
I'm not looking to remove obscenities automatically... for my web app, I want to be notified if a word I deem "bad" is used.
Much as the replacement portion above, you can see if something matches like so:
public bool HasBadWords(string inputWords) {
Regex wordFilter = new Regex("(puppies|kittens|dolphins|crabs)");
return wordFilter.IsMatch(inputWords);
}
It will return true if the string you passed to it contains any words in the list.
At my job we put some automatic bad word filtering into our software (it's kind of shocking to be browsing the source and suddenly run across the array containing several pages of obscenity).
One tip is to pre-process the user input before testing against your list, in that case that someone is trying to sneak something by you. So by way of preprocessing, we
uppercase everything in the input
remove most non-alphanumerics (that is, just splice out any spaces, or punctuation, etc.)
and then assuming someone is trying to pass off digits for letters, do the something like this: replace zero with O, 9 with G, 5 with S, etc. (get creative)
And then get some friends to try to break it. It's fun.
You could consider using the HashKey objects or Dictionary<T1, T2> instead of the array as using a Dictionary for example can make code more efficient, because the .Contains() method becomes .Keys.Contains() which is way more efficient. This is especially true if you have a large list of profanities (not sure how many there are! :)

Convert string to char

I get from another class string that must be converted to char. It usually contains only one char and that's not a problem. But control chars i receive like '\\n' or '\\t'.
Is there standard methods to convert this to endline or tab char or i need to parse it myself?
edit:
Sorry, parser eat one slash. I receive '\\t'
I assume that you mean that the class that sends you the data is sending you a string like "\n". In that case you have to parse this yourself using:
Char.Parse(returnedChar)
Otherwise you can just cast it to a string like this
(string)returnedChar
New line:
string escapedNewline = #"\\n";
string cleanupNewLine = escapedNewline.Replace(#"\\n", Environment.NewLine);
OR
string cleanupNewLine = escapedNewline.Replace(#"\\n", "\n");
Tab:
string escapedTab = #"\\t";
string cleanupTab= escapedTab.Replace(#"\\t", "\t");
Note the lack of the literal string (i.e. i did not use #"\t" because that will not represent a Tab)
Alternatively you could consider Regular Expressions if you need to replace a range of different string patterns.
You should probably write a utility function to encapsulate the common behaviour above for all the possible Escape Sequences
Then you'd write some Unit Tests to cover each of the cases you can think of.
As you encounter any bugs you add more unit tests to cover those cases.
UPDATE
You could represent a tab in the XML with a special character sequence:
see this article
This article applies to SQL Server but may well be relevant to C# also?
To be absolutely sure, you could try generating a string with a tab in it and putting it into some XML (programmatically) and using XmlSerializer to serialize that to a file to see what the output is, then you can be sure that this will faithfully 'round-trip' the string with the tab still in it.
how about using string.ToCharArray()
You can then add the appropriate logic to process whatever was in the string.
char.parse(string); is used to convert string to char and you can do vice versa
char.tostring();
100% solved

Quick & Dirty way to update "IDs" in a string formatted as XML (C#)

For a one-shot operation, i need to parse the contents of an XML string and change the numbers of the "ID" field. However, i can not risk changing anything else of the string, eg. whitespace, line feeds, etc. MUST remain as they are!
Since i have made the experience that XmlReader tends to mess whitespace up and may even reformat your XML i don't want to use it (but feel free to convince me otherwise). This also screams for RegEx but ... i'm not good at RegEx, particularly not with the .NET implementation.
Here's a short part of the string, the number of the ID field needs to be updated in some cases. There can be many such VAR entries in the string. So i need to convert each ID to Int32, compare & modify it, then put it back into the string.
<VAR NAME="sf_name" ID="1001210">
I am looking for the simplest (in terms of coding time) and safest way to do this.
The regex pattern you are looking for is:
ID="(\d+)"
Match group 1 would contain the number. Use a MatchEvaluator Delegate to replace matches with dynamically calculated replacements.
Regex r = new Regex("ID=\"(\\d+)\"");
string outputXml = r.Replace(inputXml, new MatchEvaluator(ReplaceFunction));
where ReplaceFunction is something like this:
public string ReplaceFunction(Match m)
{
// do stuff with m.Groups(1);
return result.ToString();
}
If you need I can expand the Regex to match more specifically. Currently all ID values (that contain numbers only) are replaced. You can also build that bit of "extra intelligence" into the match evaluator function and make it return the match unchanged if you don't want to change it.
Take a look at this property PreserveWhitespace in XmlDocument class

Categories

Resources