![]() |
|
[C#] Using array format with strings - Printable Version +- Hack Forums (https://hackforums.net) +-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444) +--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151) +---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118) +---- Thread: [C#] Using array format with strings (/showthread.php?tid=4991215) |
Using array format with strings - guycheap - Sep 17, 2015 Hey Everyone, I'm still a relatively new C# programmer but I'd love to help other programmers who may not be familiar with something like this. This is a great way to organize stings in a format where it's easily accessible instead of having to scroll through a bunch of things, it also makes things like text to command easier. Without wasting time here's the format to get started: Code string soandso = String.Format("",blah,blah);To analyze this, we are first declaring the string soandso, after that we are setting a blank value for the string although that is not the purpose. Lastly we are using the array system to link something that's currently non existent 👹. Remember the array system starts with 0. Let's take up a normal example of this: Code string soandso = String.Format("Hi {0} How's it going? It's a {1} day out today huh?", "joe", "nice");Now let's use this for user input from a textbox. Code string soandso = String.Format("Hey {0} I'm {1}, I am {2} years old and currently live in {3}.", textbox1.text, textbox2.text, textbox3.text, textbox4.text);That's all. Happy programming everyone. * - BahNahNah - Sep 17, 2015 You can actually do a whole lot more with string.format. Code decimal[] prices = new decimal[] {100m, 124.99m, 1.24m };Will output: Quote:Index 0 $100.00 It uses this formatting: Quote:{index[,alignment][ :formatString] } So for the "{1, 12:C2}" example: The 1 is just getting the value at index 1 (like normal) Then the ",12" is adding a 12 character spacing Finally the ":C2" is formatting the number as currency to two decimal points. You can also use the :formatString to pass in .ToString arguments. Code Guid id = Guid.Empty;Will output the standard id.ToString() Quote:000000-0000-0000-0000-000000 But we can pass in some arguments Code Guid id = Guid.Empty;outputs Quote:000000 just like this would: Code Console.WriteLine(id.ToString("n"));More: MSDN * - Odus - Sep 18, 2015 BahNahNah beat me to it, there's a lot more you can do with Format. Buuut with C# 6.0 we get some cool new interpolation sugar: Code string name = "Odus";* - guycheap - Sep 18, 2015 Excellent examples guys. I'll be sure to add them all in the OP when I'm home :). * - Carlsson94 - Sep 18, 2015 You can also use string interpolation. This Code string soandso = String.Format("Hi {0} How's it going? It's a {1} day out today huh?", "joe", "nice");Code string soandso = $"Hi {"joe"} How's it going? It's a {"nice"} day out today huh?"; |