Vinoth
Vinoth

Reputation: 13

I want to split the string and should get specific text using C#

I want to split the string and to get specific text("Kernal Ltd") using split functionality. This is my following string,

Your Quote - 12345- Kernal Ltd

Tried to split the string with empty string and tried to get the string by index

var companyName = this.renewalSummaryPage.QuoteNameField.GetText().Split(
            new string[] { " " }, StringSplitOptions.None);
        Assert.AreEqual(CommonMessages.CompanyName, companyName[5]+" "+ companyName[6]);

Expected to get string of :

Kernal Ltd

Actual:

index outside the bounds of the array error

Upvotes: 0

Views: 138

Answers (3)

David Bentley
David Bentley

Reputation: 864

You should probably provide more context. If this is something reusable and the format is always the same, you could split and trim based on the '-' character. This will work assuming you do not have '-' in your company names. Remember this will FAIL if the format is not the same for your input.

var companyName = this.renewalSummaryPage.QuoteNameField.GetText().Split('-').LastOrDefault().Trim();

Now, if you have '-' characters in the company name...you can do the following. This will rebuild the string with the company name if '-' characters exist.

string[] parts = text.Split('-');
if (parts.Length > 2)
{
    companyName = string.Join("-", parts.Skip(2)).Trim();
}
else
{
    companyName = parts.LastOrDefault().Trim();
}

Upvotes: 0

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112392

If you split by spaces, then you will get "Kernal" and "Ltd" as two distinct entries. Split by '-' and don't rely on a specific number of parts. Instead look for the length of the resulting array.

string[] parts = "Your Quote - 12345- Kernal Ltd".Split('-');
string name = parts[parts.Length - 1].Trim(); // ==> "Kernal Ltd"

Array indexes are zero-based and range from 0 to Length - 1.

Or with Linq

string[] parts = "Your Quote - 12345- Kernal Ltd".Split('-');
string name = parts.Last().Trim();

Note that String.Split returns always at least one item. If the input string does not contain the split character(s), the whole string is returned in an array of length 1.

Upvotes: 1

pappbence96
pappbence96

Reputation: 1204

Your indices are off by one. You have 5 spaces in the string, so that will result in 6 strings after Split(" "). So you have to access companyName[4] and companyName[5].

A more elegant solution would be:

int last = companyName.Count;
string companyNameString = companyName[last - 1] + " " + companyName[last];

But the best solution, assuming the format is always the following:

<string> - <number> - <company name>

is:

string companyName = this.renewalSummaryPage.QuoteNameField.GetText().Split("-").LastOrDefault();

Upvotes: 0

Related Questions