Ben
Ben

Reputation: 25817

How create substring when i know first and last characters in the string with C#?

I am new in C# please help to write in efficient C# way.

The case(always first character is '-' and the last is '>'):

Example 1:

input:   bdfdfd-wr>
output:  wr

Example 2:

input:   -dsdsds-sdsds-grtt>
output:  grtt

Example 3:

input:   -dsdsds-sdsds-grtt>><>>dfdfdfd
output:  grtt

Example 4:

input:   -dsdsds-sdsds-grtt>><->>df-d=fdfd
output:  grtt

Upvotes: 0

Views: 294

Answers (6)

Zen
Zen

Reputation: 244

     string input = "-dsdsds-sdsds-grtt>";
     int startInd = input.LastIndexOf('-');
     int endInd = input.IndexOf('>', startInd);
     string result;
     if (startInd < endInd) 
         result = input.Substring(startInd + 1, endInd - startInd - 1);

EDIT:

    string input = "-dsdsds-sdsds-grtt>><->>df-d=fdfd";
    string str = input.Substring(0, input.IndexOf('>'));
    string result = str.Substring(str.LastIndexOf('-') + 1);

Using linq seems to be also a good option:

var result = input.Split('>').First().Split('-').Last();

Upvotes: 1

sloth
sloth

Reputation: 101122

You can use regular expressions.


Example:

var r = new Regex(@"-(\w*)>");

var inputs = new [] { "bdfdfd-wr>",
                      "-dsdsds-sdsds-grtt>",
                      "-dsdsds-sdsds-grtt>><>>dfdfdfd",
                      "-dsdsds-sdsds-grtt>><->>df-d=fdfd" };

foreach(var i in inputs)
    Console.WriteLine(r.Match(i).Groups[1].Value);

Output:

wr
grtt
grtt
grtt

Upvotes: 1

cuongle
cuongle

Reputation: 75316

LINQ style:

var output = input.Split('>').First().Split('-').Last();

Upvotes: 1

horgh
horgh

Reputation: 18553

        string s = "-dsdsds-sdsds-grtt>";
        string output = null;
        if (s.Contains(">"))
        {
            output = s.Split(new string[] { ">" }, 
                             StringSplitOptions.RemoveEmptyEntries)
                      .FirstOrDefault(i => i.Contains("-"));
            if (output != null)
                output = output.Substring(output.LastIndexOf("-") + 1);
        }

Returns the first-in-line text wrapped into - and >. If input is "-dsdsds-sdsds-grtt>asdas-asq>", it will return grtt; for -dsdsds-sdsds-grtt>><>>dfdfdfd - returns grtt as well

There you can find a great deal of methods to work with strings.

Upvotes: 1

Sjoerd
Sjoerd

Reputation: 75629

I can think of two ways:

  • Use a regex, something like -([a-z]+)>. The result would then be in Match.Groups[1].
  • Use IndexOf to find the >, use LastIndexOf to find the last dash, and then use Substring to get the word.

Upvotes: 1

Brian Warshaw
Brian Warshaw

Reputation: 22974

string example = "-dsdsds-sdsds-grtt>";
int lastIndexOfHyphen = example.LastIndexOf("-");
int indexOfBracket = example.IndexOf(">", lastIndexOfHyphen);
string substr = example.Substring(lastIndexOfHyphen + 1, indexOfBracket - lastIndexOfHyphen - 1);

Upvotes: 2

Related Questions