-5

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'
Rudi Visser
  • 21,350
  • 5
  • 71
  • 97
ahodder
  • 11,353
  • 14
  • 71
  • 114
  • 5
    Why don't you look into the documentation of the [`System.String`](http://msdn.microsoft.com/en-us/library/system.string%28v=vs.100%29.aspx) and [`System.Text.StringBuilder`](http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx) classes? – O. R. Mapper Aug 02 '12 at 22:47
  • @O.R.Mapper I understand there is StringBuilder; like I said it is easy to do this normally, I'm looking for stuff like my first or third examples. You cannot do this with a string builder. – ahodder Aug 02 '12 at 22:50
  • You would have to write your own extension methods. – Marlon Aug 02 '12 at 22:51
  • @AedonEtLIRA: If you had read the docs, you would know that the [`Substring` method](http://msdn.microsoft.com/en-us/library/hxthx5h6.aspx) does exactly what you show in your first example. For the third example, there is indeed no single method if your repeated string has more than one character and an extension method would be the way to go, as pointed out by StackUnderflow. – O. R. Mapper Aug 02 '12 at 22:56

4 Answers4

4

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.

Community
  • 1
  • 1
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • the cyhicken one can be done with `if ("something chickin".Contains("chickin")` or `if ("something chickin".IndexOf("chicken") > -1)` – oscilatingcretin Aug 02 '12 at 22:53
  • @oscilatingcretin Yes - you're just calling `String.Contains`, though - there's no language level support helping you here. – Reed Copsey Aug 02 '12 at 22:54
  • @pst Well, I'd argue that "in", the multiplication, and slice notation are all language functions in Python (ie: they work in IronPython or Jython, etc - not just CPython, and there's no direct support in the framework for it). – Reed Copsey Aug 02 '12 at 23:01
  • @ReedCopsey Ah yes, wasn't thinking the IronPython sense.. –  Aug 03 '12 at 00:08
2

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.

Community
  • 1
  • 1
Andras Zoltan
  • 41,961
  • 13
  • 104
  • 160
  • +1 for opposing 'string' * 5 - I've worked in too many loosely typed languages that "help" you in ways that lead to data-dependent bugs. The strange thing is that in those languages you have to be _more_ careful with data types to avoid unexpected behaviour. – christutty Jan 09 '16 at 06:34
2

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.

Community
  • 1
  • 1
Jeremy Wiggins
  • 7,239
  • 6
  • 41
  • 56
1

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...
Mr. B
  • 365
  • 1
  • 10
  • This doesn't use LINQ at all. This is just standard String.Contains... (It works, but it's not using anything related to LINQ) – Reed Copsey Aug 02 '12 at 23:16
  • Yeah, sorry. This was my first post... I had some other examples in there but didn't insert them as a code block, so it complained, then I tried again, figured out how to get it to accept code with a single code statement (the one you see), doesn't make much sense now but I got a vote (I think) so I didn't want to take it down :). Also, it doesn't let you take it down, just vote to delete? – Mr. B Aug 03 '12 at 16:17