Can anyone give me an example of spintax snippet for C# / VB.NET programming language. If you don't know what that is (the spintax), well basically it is a way of putting different values of strings and then randomly choosing one. For instance:
{Hello|Hi|Greetings} my name is {Tom|John|Eaven} and I like {turtles|programming|ping pong}.
And it would choose between { } splitting those strings inside of the {} string with delimiter of | so it randomly outputs the final string.
Here is a class for C# which handles that snippet:
public class Spinner
{
private static Random rnd = new Random();
public static string Spin(string str)
{
string regex = #"\{(.*?)\}";
return Regex.Replace(str, regex, new MatchEvaluator(WordScrambler));
}
public static string WordScrambler(Match match)
{
string[] items = match.Value.Substring(1, match.Value.Length - 2).Split('|');
return items[rnd.Next(items.Length)];
}
}
And try it:
Console.WriteLine(Spinner.Spin("{Hello|Greetings|Merhaba} World, My name is {Beaver|Michael} Obama"));
Here is the complete article: http://jeremy.infinicastonline.com/2010/11/spintax-class-for-c-net/
Related
Let's say I have the following code point: u1F64A (which is the 🙊 emoji).
This can be written as:
string monkey = "\u1F64A";
How would I convert a known codepoint (as an integer) to a string at runtime though?
int codepoint = 0xF64A;
string monkey = //?
When I want to play with Emojis in C#, I build a helper class just like this:
public class Emoji
{
readonly int[] codes;
public Emoji(int[] codes)
{
this.codes = codes;
}
public Emoji(int code)
{
codes = new int[] { code };
}
public override string ToString()
{
if (codes == null)
return string.Empty;
var sb = new StringBuilder(codes.Length);
foreach (var code in codes)
sb.Append(Char.ConvertFromUtf32(code));
return sb.ToString();
}
}
This way, I can just do string monkeyEmoji = new Emoji(0xF64A);
It also supports emojis with multiple code points (yes, those exist and are a pain)
Is the above code even compilable? It doesn't compile on my machine.
And why should it, \u1F64A is not a valid string.
I think what could work is string monkey = $"{char.ConvertToUtf32((char) 0xF64, 'A')}", but that is just a guess. I just answered to clarify that the first line of code you wrote is not compilable on my machine.
I have a alphanumeric string of array which contains some characters at end of string also. The problem is i'm able to sort only till before the last character.
Here is the my array
string[] ar = new string[] { "DV00154A", "DV00144A", "DV00111B", "DV00100A", "DV00199B", "DV00001A" };
i have tried some method but the sorted array skipping the sorting of last character. here is one of the approach which i have tried.
public static string ArraySort(string input)
{
return Regex.Replace(input, "[0-9]+", match => match.Value.PadLeft(10,'0'));
}
public static void Main(string[] args)
{
string[] ar = new string[] { "DV00154A", "DV00144A", "DV00111B", "DV00100A",
"DV00199B", "DV00001A" };
var result = ar.OrderBy(x => ArraySort(x));
Console.WriteLine(string.Join(",",result.ToArray()));
}
which returning the below output
DV00001A,DV00100A,DV00111B,DV00144A,DV00154A,DV00199B
but the output i need should be like this
DV00001A,DV00100A,DV00144A,DV00154A,DV00111B,DV00199B
What about this solution:
public static string ArraySort(string input)
{
return $"{input.Substring(0, 2)}{input.Substring(7, 1)}{input.Substring(2, 5)}";
}
public static void Main(string[] args)
{
string[] ar = new string[] { "DV00154A", "DV00144A", "DV00111B", "DV00100A", "DV00199B", "DV00001A" };
Array.Sort(ar, (a, b) => StringComparer.OrdinalIgnoreCase.Compare(ArraySort(a), ArraySort(b)));
Console.WriteLine(string.Join(",", ar));
Console.ReadKey();
}
The ArraySort method rearranges the values in a sortable format: DV00154A -> DVA00154. That values are used the by the Array.Sort comparer method.
The only disadvantage that the ar array is sorted in-place...
Edit:
I found an even better solution: just take my ArraySort method with your Main method. Should work just fine. :) And it will not affect your ar array.
Edit 2:
Just fixed a little bug in my ArraySort method. (Sorry.)
Edit 3:
If you can ignore the DV-prefix, you could change the ArraySort method to this:
public static string ArraySort(string input)
{
return $"{input.Substring(7, 1)}{input.Substring(2, 5)}";
}
The logic is less complex and the resulting values are shorter. It should have a (marginal) better performance.
I need help for this exercise:
Inside the Test class, you must create a public method called copyText that takes a text as input and answer with a text.
It must answer with the same text put together as many time as there is characters in the input text.
Ex: in("car") out "carcarcar";
Ex: in("it") out "itit";
Ex: in("love") out "lovelovelovelove";
Ex: in("coffe") out "coffecoffecoffecoffecoffe";
I have tried to make a solution, where I find the Length of the word,
but I can't figure out to do this part:
Answer with the same text put together as many time as there are characters:
class Program
{
static void Main(string[] args)
{
Test k = new Test();
string carText = k.copyText("car");
Console.WriteLine(carText.Length);
}
}
class Test
{
public string copyText(string text)
{
return text;
}
}
You can loop through each character in the word, and append the text each time to a variable.
public string copyText(string text)
{
string output = String.Empty;
for(int i = 0; i < text.Length; i++) {
output += text;
}
return output;
}
It is good to point out that the String class is immutable and for every iteration new object will be created, which can cause high memory consumption. For concatenating strings see the StringBuilder class. I think this article will help you with your exercise.
PS: I also think you should not just copy the snippet, but really research and try to understand how it works. Then when you have more questions than answers, it will cause more and more research and actually learning.
Good luck with the coding :)
Im making a hangman game, at the start of the game the word that the player must guess is printed as stars. I have just started making it again after attempting to write it once and just having messy code that i couldn't bug fix. So I decided it best to write it again. The only problem is, when i try to get my array to print out by using array.ToString(); it just returns System.char[]. See below.
code:
class Program
{
static void Main(string[] args)
{
string PlayerOneWord;
string PlayerTwoGuess;
int lives = 5;
Console.WriteLine("Welcome to hangman!\n PLayer one, Please enter the word which player Two needs to guess!");
PlayerOneWord = Console.ReadLine().ToLower();
var stars = new char[PlayerOneWord.Length];
for (int i = 0; i < stars.Length ; i++)
{
stars[i] = '*';
}
string StarString = stars.ToString();
Console.Write("Word to Guess: {0}" , StarString);
Console.ReadLine();
}
}
output:
The output should say Word to guess: Hello.
Please will someone explain why this is happening as its not the first time I have run into this problem.
Calling ToString on a simple array only returns "T[]" regardless what the type T is. It doesn't have any special handling for char[].
To convert a char[] to string you can use:
string s = new string(charArray);
But for your concrete problem there is an even simpler solution:
string stars = new string('*', PlayerOneWord.Length);
The constructor public String(char c, int count) repeats c count times.
The variable stars is an array of chars. This is the reason you get this error. As it is stated in MSDN
Returns a string that represents the current object.
In order you get a string from the characters in this array, you could use this:
Console.Write("Word to Guess: {0}" , new String(stars));
The correct way to do this would be:
string StarString = new string(stars);
ToString() calls the standard implementation of the Array-class's ToString-method which is the same for all Arrays and similarily to object only returns the fully qualified class name.
Try this code:
static string ConvertCharArr2Str(char[] chs)
{
var s = "";
foreach (var c in chs)
{
s += c;
}
return s;
}
I am trying to split a string and assign the different values. The string it returns to me is:
0077|PCK|PRD|05025066840471|4|Can Opener|1|10|B|20.00|0|100|0|0.00|0|0|1|0|0
So I want to split the string on "|" and assign each of them to another variable. That is what I tried to do:
public static void LoadPRD(string sData)
{
string[] s = null;
prdType PRD = new prdType();
s = sData.Split("|");
PRD.bCode = s.Left(s[0], 14);
PRD.PCode = s.Left(s[1], 12);
PRD.Desc = s.Left(s[2], 40);
PRD.Pack = s.Val(s[3]);
PRD.Unit = s.Left(s[4], 12);
PRD.VATCode = s.Left(s[5], 1);
PRD.VATRate = Conversion.Val(s[6]);
PRD.Cost = Conversion.Val(s[7]);
PRD.Sell = Conversion.Val(s[8]);
PRD.Stock = Conversion.Val(s[9]);
PRD.AWS = Conversion.Val(s[10]);
PRD.OnOrder = Conversion.Val(s[11]);
PRD.OrderQty = Conversion.Val(s[12]);
PRD.LabelQty = Conversion.Val(s[13]);
PRD.Restriction = s.Left(s[14], 1);
PRD.MinStock = s.Val(s[15]);
PRD.PromoCode = s.Left(s[16], 3);
PRD.MnM = s.Left(s[17], 3);
}
The error message says that the Strings does not exist in the context, but it is not too of a helpful information, I do understand what it means but I am very confused on how to approach the solution.
Just so you know, I did create the variable before hand, I've posted them below:
public struct prdType
{
public string bCode;
public string PCode;
public string Desc;
public Int16 Pack;
public string Unit;
public string VATCode;
public float VATRate;
// Stored in pence
public long Cost;
public long Sell;
public long Stock;
public float AWS;
public long OnOrder;
public long OrderQty;
public long LabelQty;
public string Restriction;
public long MinStock;
public string PromoCode;
}
Your help will be much appreciated.
Thanks.
EDIT:
On
s = sData.Split("|");
it says: "The best overloaded method match for string.Split(params char[]) has some invalid arguments. It also says that arguments cannot be converted to char. Any ideas?
Rather than use legacy VB methods for this, I would suggest using C# methods all the way.
string[] s = sData.Split('|');
The use of Strings.Left is not readily apparent. Since you've already split the line, you'll have each element of the split in its entirety. If you want to take only the first n characters, you can do that, but there is no built-in equivalent for Strings.Left in C#.
For those elements that are a different type, you can use Convert.ToX:
PRD.Pack = Convert.ToInt16(s[3]));
PRD.VATRate = Convert.ToSingle(s[6]));
PRD.Cost = Convert.ToInt64(s[7]);
And so on. Note that float uses Convert.ToSingle, not Convert.ToFloat.
ADDED
Based on #Raphael's comment, Convert.ToX is not a direct replacement for Conversion.Val(), but as long as the string is strictly numeric you will be ok and will get the correct type.
These methods come from Microsoft.VisualBasic namespace.It should be only used if you know what you're doing (see Tim's comment on this answer).
I wouldn't advise you to use these methods.
They are equivalent methods in c# (or they're rather easy to implement).
Like String.Split, for example (so you could do var s = sData.Split('|'); )
A way to do something equivalent to String.Left
Wouldn't advise to do this, but anyway :
If you want absolutely use them, you should :
Add a reference to Microsoft.VisualBasic assembly (right click on project's references, you should find it in Framework libs)
Add the right using at the top of your code : using Microfost.VisualBasic;
You need to do s = sData.Split('|');