Click here to Skip to main content
15,915,828 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have string "The ticket has created with the number TS894858 use in your reference"

in the above string i want to get "TS894858" and show some where.

Could you please help me that how to get in simple way.

What I have tried:

I have tried
C#
public static string getBetween(string strSource, string strStart, string strEnd)
{
    int Start, End;
    if (strSource.Contains(strStart) && strSource.Contains(strEnd))
    {
        Start = strSource.IndexOf(strStart, 0) + strStart.Length;
        End = strSource.IndexOf(strEnd, Start);
        return strSource.Substring(Start, End - Start);
    }
    else
    {
        return "";
    }
}


But this is very complex.
Posted
Updated 11-May-16 1:16am
v2

Not really that complex. Use String.Split to separate the string into an array, and then search through the array for one beginning with TS, and containing numbers. Something like:
C#
String[] words = strText.Split(' ');
int value;
foreach (string word in words)
{
    if (word.StartsWith("TS") && int.TryParse(word.Substring(2), out value))
    {
        // looks like you got the value
        Console.WriteLine("found: {0}", word);
    }
}
 
Share this answer
 
Simpler one.
C#
public static string getBetween(string strSource, string strStart, string strEnd)
       {
         return  strSource.Replace(strStart, "").Replace(strEnd, "").Trim();
       }


with Validation:

C#
public static string getBetween(string strSource, string strStart, string strEnd)
       {

           if (!string.IsNullOrWhiteSpace(strSource) && !string.IsNullOrWhiteSpace(strStart) && !string.IsNullOrWhiteSpace(strEnd))
               return strSource.Replace(strStart, "").Replace(strEnd, "").Trim();
           return "";
       }
 
Share this answer
 
v2
In this case you might be able to use a regular expression, but it depends on the format of your string.
If the string always contains the pattern "... number <ticket number> ....", then you can use the code below.
C#
// Add to the beginning of the file
using System.Text.RegularExpressions;

// The expression
// It basically say get any word containg letters and numbers 
// directly after the word "number" and a space
Regex regex = new Regex(@"number\s+(?<no>[\w\d]+)\s", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

string text = "The ticket has created with the number TS894858 use in your reference";
Match m = regex.Matches(text);
if (m.Success)
{
    string ticketNumber = m.Groups["no"].Value;
    // Do some stuff
}
else
{
    // No ticket number was found
}

There are other possibilities too, but without more sample data it is difficult to give a better solution.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900