c# string tricks/features? [closed] - c#

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have always hated string parsing, something I am doing a lot of in a current project.
Does c# have and tricks or quick features for strings that would make my life easier? In particular cropping, multiplying or substringing? The end goal here is to take a list of string and turn it into a nice pretty columned structure. Easy, but still, I would it to be python easy.
For example, python has:
>>> a = "I once was a string, then I got mutilated"
>>> print a[20:]
then I got mutilated
or
>>> 'chicken' in 'chicken noodle soup'
True
or finally
>>> 'lol' * 5
'lollollollollol'

There aren't language related features for this in C# like there are in Python. The only real C# language feature with strings is allowing + to be mapped to String.Concat, to simplify (and keep efficient) "a" + "b" + "c" statements.
The String class provides this functionality via methods, however. There is also StringBuilder, which is used for building large strings based on multiple concatenations.
In your example, see String.Substring for slicing and String.Contains for in. There isn't a simple "repeat" style operation like the multiplication in Python.
That being said, it's easy to make an extension method which handles the multiply functionality.

They're different languages - the syntax is different and comparing C# to Python in this way is largely pointless. Also I completely challenge your assertion that the examples you've given are 'easier'.
I don't see how you can get much easier than:
Console.WriteLine("Foo".Substring(1)); //<-- prints 'oo'
Console.WriteLine("chicken noodle soup".Contains("chicken")
.ToString()); //<-- prints 'true'
And for the last one, read this SO: Can I "multiply" a string (in C#)?
Personally, in particular, I hate the idea of multiplying a string - too much ambiguity if that value happens to be '5' - hiding such functionality behind operators smells.

First Question
You can use String.SubString():
string a = "I once was a string, then I got mutilated";
string lastTwentyCharactersOfA = a.Substring(Math.Max(0, a.Length - 20));
// returns "then I got mutilated"
Credit where credit is due: This answer does a nice job of making sure that you don't get an exception if your string has less characters than you are requesting.
Second Question
You can use String.Contains():
string soup = "chicken noodle soup";
bool soupContainsChicken = soup.Contains("chicken"); // returns True
Third Question
You can't override the multiplication operator for the String class. It's a sealed class, and of course you don't have access to the source code to make it a partial class or something along those lines. You have a couple of options that will get you close to what you want to do. One is to write an extension method:
public static string MultiplyBy(this string s, int times)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < times; i++)
{
sb.Append(s);
}
return sb.ToString();
}
Usage:
string lol = "lol";
string trololol = lol.MultiplyBy(5); // returns "lollollollollol"
Or if you want to go the route of operator overloading, you can write a custom String class of sorts and then have at it.
public struct BetterString // probably not better than System.String at all
{
public string Value { get; set; }
public static BetterString operator *(BetterString s, int times)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < times; i++)
{
sb.Append(s.Value);
}
return new BetterString { Value = sb.ToString() };
}
}
Usage:
BetterString lol = new BetterString { Value = "lol" };
BetterString trololol = lol * 5; // trololol.Value is "lollollollollol"
In general, there's a lot you can do with System.String and System.Text.StringBuilder. And the possibilities are almost endless with extension methods. Check out MSDN if you are interested in learning the ins and outs of it all.

using linq, you can treat your string like a list of chars and do what you want easy enough.
var chickenString = "chicken noodle soup";
var hasChicken = chickenString.Contains("chicken");
// hasChicken = true at this point...

Related

Negative value in string based C# Calculator

I'm relatively new to programming, and I'm currently working on a C# string based calculator. A lot of it works fine already, but I'm having problems with negative coefficients. My calculator engine always looks for the next operator and calculates accordingly, so the problem is that if I want to calculate "-5+6", the first operation is "-5", but it obviously can't be calculated. How can I separate operator and coefficient?
What I've come up with so far (small extract of the whole code)
if (nextOperation.Contains("+"))
{
string firstOperationResult = Calculate(nextOperation.Split('+').ToList(), "+")[0];
string partialFormulaReplacement = partialFormula.Replace(nextOperation, firstOperationResult);
return CalculateDashOperation(partialFormulaReplacement);
}
else if (nextOperation.Contains("-") && nextOperation.IndexOf("-") > 0)
{
string resultOfFirstOperation = Calculate(nextOperation.Split('-').ToList(), "-")[0];
string partialFormulaReplacement = partialFormula.Replace(nextOperation, resultOfFirstOperation);
return CalculateDashOperation(partialFormulaReplacement);
}
//added
else if (nextOperation.Contains("-") && nextOperation.IndexOf("-") == 0)
{
//what to do
}
//added
return partialFormula;
"-5" can be treated as meaning "0-5", so you could say there's an implicit zero if you see an operand in the first position of the string. Note that this approach will only work for the operators + and -.
As for the problem of attempting to calculate "-5" again, I suggest you use the 0 as an argument to your Calculate function, rather than prepending it to the string you're processing:
Calculate(new List<string>{"0", nextOperation[1]}, "-")
Also, as has been pointed out in the comments, this approach will not cover all possible cases, and if this isn't an academic exercise then there are solutions out there that already solve this problem.
The sample code looks a little short. But let's try to suggest:
nextOperation is a string containing something like "1 * -6 + 6"
In order to evaluate this expression yout have to 'encrypt' your string first.
The topic you are looking for is parenthesis
A nice explanation of the basic (in python) can be found here.
But this question is already answered here.
Use NCalc Library:
Dont reinvent wheel, * and / priorities is already implemented.
Simple expressions
Expression e = new Expression("2 + 3 * 5");
Debug.Assert(17 == e.Evaluate());
Handles mathematical functional from System.Math
Debug.Assert(0 == new Expression("Sin(0)").Evaluate());
Debug.Assert(2 == new Expression("Sqrt(4)").Evaluate());
Debug.Assert(0 == new Expression("Tan(0)").Evaluate());

richtextbox application test c# [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm very new to c#. I created a forms. A richtextbox and a button in it.
I have a list of operators: Sum, Subtract,Multi,Div.I want to run a small richtextbox test. For example,in the richtextbox I write a text (eg. Sum(1,2)) and then click the button. A return result(eg.3) prints in the richtextbox.
My idea is to use string contains
foreach( var element in operatorlist)
{
string text=richtextbox.text;
if( text.contains(element)== true)
{
element(parameter1,parameter2);//something like this
}
}
I met two questions right row.
My first question is how to get the mathematical operation from the richtextbox text. Is there a better way than mine?
My second question is once we know the operator,how to allocate the two parameters in the richtextbox to the operator.
I'm not asking for coding, I'm just looking for ideas. If you have a good idea and wish to share.
You can evaluate an expression using the DataTable.Compute function:
int p1 = 1 ; string s1 = p1.ToString() ;
int p2 = 2 ; string s2 = p2.ToString() ;
int p3 = 3 ; string s3 = p3.ToString() ;
// Compute (p1+p2)*p3 ==> 9
int result = new DataTable().Compute( "("+s1+"+"+s2+")*"+s3+")","") ;
or directly:
string expression = "(1+2)*3" ;
int result = new DataTable().Compute(expression,"") ;
I think this comes down to personal style. Your way will definitely work, so good on you for that. The way I would do it is to create a Dictionary of strings to an enum. So for example, said dictionary and enum might look like this:
enum Operator { Addition = 0, Subtraction = 1, Multiplication = 2, Division = 3, etc};
var operatorDictionary = new Dictionary<string, Operator>()
{
{"Addition", Operator.Addition},
{"Subtraction", Operator.Subtraction},
etc...
};
Then to get the value you would just do
Operator operation;
operatorDictionary.TryGetValue(string operationString, out operation);
and you would have to then build some code that switches through the Operators and performs the correct operation. There is even a way of converting a string to an enum, so that would work as well.
It looks like the parameters are in a consistent format, so you would just make a simple method that splits by parenthesis and the comma, and returns the strings that it found.
Let me know if you need anything explained more.

TryParse dilemma-Dealing with out parameters [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I never liked out and ref parameters.When I see them in action they give me a feeling that something is messy about the design.
I thought that the only exception was the so called TryXXX pattern that returns a boolean as the function result (whether everything was fine or something went wrong) and an out parameter for the real result, until I read this article today and It made me think if there's a better pattern to implement this kind of methods.
I thought that we could either have a function that returns more than one result(or as the article says a tuple)
Tuple<Exception,T> TryParseT(object obj)
or a function that accepts a callback function for success :
void TryParseT(object obj,Action<T> success)
The question is , which one is better from a functional design point of view ?
UPDATE :
To rephrase my question , I want to know which of these two functions more complies with Functional Programming principles and why ?
Essentially the problem is that to follow the functional programming approach you should always provide a return value for an input value. So the returning void route isn't the way to go. You need to return a value that can represent success (and hold the successful result) and failure (and hold no result).
The closest to that is where you have returned a Tuple which includes the exception. However you then don't have the 'infrastructure' to deal with the Tuple reliably once you've got it. So the code scaffolding around it will be repeated.
Take a look at this library language-ext. It deals with improving the out problem for TryParse using its implementation of Option<T>.
string inp = "123";
// Attempts to parse the value, uses 0 if it can't
int value1 = parseInt(inp).IfNone(0);
// Functional alternative to above
// Attempts to parse the value, uses 0 if it can't
int value2 = ifNone(parseInt(inp), 0);
// Attempts to parse the value and then pattern matches the result
int value3 = parseInt(inp).Match(
Some: x => x * 2,
None: () => 0
);
// Functional alternative to above
// Attempts to parse the value and then pattern matches the result
int value4 = match( parseInt(inp),
Some: x => x * 2,
None: () => 0
);
The library also allows you to just check that something is valid:
if( parseInt(inp) )
return 1;
else
return 0;
And allows for comparisons without actually extracting the value:
if( parseInt(inp) == 123 )
return 123;
else
return 0;
As well as logical operations:
var allValid = parseInt(x) && parseInt(y) && parseInt(z);
var someValid = parseInt(x) || parseInt(y) || parseInt(z);
And finally LINQ expressions which can often remove the need for if-then-else or matching:
var res = from x in parseInt(inp1)
from y in parseInt(inp2)
from z in parseInt(inp3)
select x + y + z;
It also has TryGetValue extensions for IDictionary, IReadOnlyDictionary, IImmutableDictionary and IImmutableSet that instead return Option<T> and can be used as above.
The most elegant method is
int Parse(string value)
The Tryxxxx methods only exist for an implementation detail named performance. If you are seeking elegance you can use the Parse method and handle any errors by failing fast.
You can instead return a tuple but this will cost an additional allocation on the heap since Tuple is a reference type.
A better solution in terms of performance (if you care) would be aKeyValuePair. But it hides (like tuple) the semantics behind generic data types which is not optimal for code clarity. A better way to signal failure than by defining some convention that the first bool of the tuple contains the failure state is by defining your own data type.
struct ParseResult<T>
{
public bool Success { get; private set; }
public T Value { get; private set; }
public ParseResult(T value, bool success):this()
{
Value = value;
Success = success;
}
}
class Program
{
static ParseResult<int> TryParse(string s)
{
int lret = 0;
if (int.TryParse(s, out lret))
{
return new ParseResult<int>(lret, true);
}
else
{
return new ParseResult<int>(lret, false);
}
}
static void Main(string[] args)
{
string test = "1";
var lret = TryParse(test);
if( lret.Success )
{
Console.WriteLine("{0}", lret.Value);
}
}
}
That approach is still quite efficient and spares you the out parameters at the cost of the allocation of a cheap container object.

Concatenate multiple strings versus String.Format [duplicate]

This question already has answers here:
String output: format or concat in C#?
(32 answers)
Closed 8 years ago.
Here is 2 methods which result the same:
public class MessageManager
{
public void SendMessage(string name, int count)
{
string message = "Hi " + name + ". I know you don't like cake, so I bought you " + count + " lollipops. Same thing, right?"; // No boxing. "count" was converted to string somehow.
//Console.WriteLine(message);
}
public void SendMessage2(string name, int count)
{
string message = String.Format("Hi {0}. I know you don't like cake, so I bought you {1} lollipops. Same thing, right?", name, count); // Boxing "name" and "count" + executing unnecessary code.
//Console.WriteLine(message);
}
}
So I guess the second method will be slower then first because of boxing and executing some additional code which inside String.Format() method.
I have tested them with following method:
public static class PerformanceTester
{
public static TimeSpan TestAction(Action<string, int> action)
{
Stopwatch timer = new Stopwatch();
timer.Start();
for (ushort i = 0; i < ushort.MaxValue; i++)
action("Alex", 1000);
timer.Stop();
return timer.Elapsed;
}
}
And here is the usage of it:
static void Main(string[] args)
{
MessageManager mm = new MessageManager();
TimeSpan ts_m1 = PerformanceTester.TestAction(new Action<string, int>(mm.SendMessage));
TimeSpan ts_m2 = PerformanceTester.TestAction(new Action<string, int>(mm.SendMessage2));
Console.WriteLine("First message took time: " + ts_m1.ToString());
Console.WriteLine("Second message took time: " + ts_m2.ToString());
Console.ReadKey();
}
Output with my Intel® Core™2 Duo Processor E8200 (DEBUG):
Output with my Intel® Core™2 Duo Processor E8200 (RELEASE):
I saw String.Format used almost everywhere (guides, blogs, tutorials etc.) but it is actually slower than simple string concatenation. I know when I talk about C# I must not care about performance, but the results in this example is too awesome.
The question is: "Is there any best practice where String.Format is actually better than concatenation of strings."
It's largely a matter of style. However, consider more complex formatting. For example you want to format a bunch of stuff:
var s = String.Format("{0,10:N2} {1,-20} {2:P2}", val, description, (val/100));
Or ...
var s = val.ToString("10:N2") + string.Format("{0,-20}", desc) + (val/100).ToString("P2");
I like the String.Format call there much better. It separates the formatting from the content in much the way that CSS separates the presentation from the HTML content. When I'm writing or examining code that formats output, I typically want to see the format at a glance. The actual values being formatted aren't relevant when I'm debugging a formatting issue.
With concatenation, I have to slog my way through the individual values to see what the format is for each item.
Finally, does performance really matter here? Most programs spend precious little time formatting their output. Optimizing the formatting code seems like a huge waste of time. Write whatever is easier to maintain and prove correct.
string.format is as the name suggest for formatting strings. you can take the format string and stick it in a resource or have it translated. it is not about performance and it is not about readability. simple string concatenation is ok if you do let's say less than 5. if you want to concatenate more strings and want to consider the performance - use StringBuilder.

how do you reverse a string in C# using LINQ? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I was reading an old post from coding horror (http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html) It's still a very entertaining read, you'll notice a lot of the people providing answers actually made small logical errors themselves (about 30% of them).
Anyway, thought I'll set myself a small challenge and found a bunch of fizzbuzz questions here: Alternate FizzBuzz Questions
"Reverse a String" - with all the built-in methods in the .net framework there are many ways to do this.
My question is:
1. how do you reverse a string using LINQ?
2. can you come up with other interesting ways of reversing a string in C#?
Here's are two examples I came up with
1. completely from scratch
2. using enumerable's reverse methods (1 liner)
private static string FromScratchSimplified(string input)
{
// constructed reversed char array
char[] reversedCharArray = new char[input.Length];
for (int i = 0; i < input.Length; i++)
{
reversedCharArray[i] = input[input.Length-1-i];
}
// build string from char array
string reversedString = new String(reversedCharArray);
return reversedString;
}
private static string UsingEnumerableReverseMethod(string input)
{
// using Enumerable.Reverse method
return new String(input.Reverse().ToArray());
}
Any more?
new string(Enumerable.Range(1, input.Length).Select(i => input[input.Length - i]).ToArray())
To keep it as close to query syntax as possible:
given:
string aString = "please reverse me";
then:
var reversed = new string((from c in aString.Select((value, index) => new { value, index })
orderby c.index descending
select c.value).ToArray());
Console.WriteLine(reversed);
yields:
em esrever esaelp

Categories

Resources