Kurkula
Kurkula

Reputation: 6762

Get substring from some char inside string

I am trying to get substring ie address from the below string

string test = "name: abc loc: xyz address: tfd details: ddd";

Is there any substring option to get only address details like "tfd"

I am trying by splitting and I think this is not the best option to get middle string.

test.Text.Split(':').LastOrDefault()

Upvotes: 1

Views: 125

Answers (5)

Danny
Danny

Reputation: 53

Simple function:

public static string GetTextBetween(string content, string start, string end)
{
    if (content.Length == 0 || start.Length == 0 || end.Length == 0)
        return string.Empty;
    string contentRemove = content.Remove(0, content.IndexOf(start, StringComparison.Ordinal) + start.Length);
    return contentRemove.Substring(0, contentRemove.IndexOf(end, StringComparison.Ordinal)).Trim();
}

Example:

GetTextBetween("name: abc loc: xyz address: Thomas Nolan Kaszas 5322 Otter LnMiddleberge FL 32068 details: ddd", "address:", "details:")

And you will get:

Thomas Nolan Kaszas 5322 Otter LnMiddleberge FL 32068

Upvotes: 3

Grumpy Cockatiel
Grumpy Cockatiel

Reputation: 51

Use some Regex pattern that fits your needs as suggested

Match m = new Regex( @"address:\s(.*)\sdetails" ).Match( test );
if ( m.Groups.Count > 0 )
    { string s = m.Groups[1].Value; }

Upvotes: 2

Cody
Cody

Reputation: 2853

I personally like the Regex solutions more, but I want to add a Non-regex one:

string test = "name: abc loc: xyz address: t f d details: ddd";
int start = test.IndexOf("address:");
int end = test.IndexOf("details:");
string adr = test.Substring(start, end-start);
Console.WriteLine(adr);

prints

t f d

So I know this version works with spaces.

Edit:

You may want to run adr.Trim() or modify the strings in the two IndexOf calls to cut out the spaces on either side of the returned string.

Upvotes: 2

Joe Beuckman
Joe Beuckman

Reputation: 2296

var parts = test.split(' ');
var keyIndex = parts.indexOf('address:');
var address = parts[keyIndex + 1];

Upvotes: 2

rory.ap
rory.ap

Reputation: 35260

Here's one approach with regular expressions:

var pattern = @"name: (\S+) loc: (\S+) address: (\S+) details: (\S+)";
var match = Regex.Match(input, pattern);
var group = match.Groups[3];
var value = group.Value;

A few assumptions:

  • The address will always be one word, i.e. no spaces,
  • The pattern will always be the same, same fields, in the same order, no difference in case in the field names, etc.

Upvotes: 2

Related Questions