简体   繁体   中英

String operation — Easiest way C#

What is the Best way to Implement the below scenario

string sample = "Mountain View XX,Lake"

Am expecting 2 scenarios as o/p

Mountain View Lake

i can get the Lake by sample.split[','][1]

what is the best way i can get the Mountain View ignoring XX

i tried with multiple splits and concatenating them also with lastIndex of !!!

So is there any other easier way ?

A string.Substring method works fine:

sample = sample.Substring(0, sample.IndexOf(","));

There is also the string.LastIndexOf to get until the last ocurrency the of a substring, for sample:

sample = sample.Substring(0, sample.LastIndexOf(","));

In your sample, both will work at the same because there is only a , char.

And after it, you could remove until the last space char.

sample = sample.Substring(0, sample.LastIndexOf(" "));

使用String.Replace

sample= sample.Replace("XX", "");

try to use regular expressions. (\\w+\\s+?\\w+)\\s+?XX\\,(\\w+) http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx group 1 contains Mountain View group 2 contains Lake

You said you tried with multiple splits. You can specify multiple separators in a single string.Split() :

var parts
    = sample.Split(new[] { "XX", "," }, StringSplitOptions.RemoveEmptyEntries);

Now you've got two pieces:

var part1 = parts[0];  // Mountain View
var part2 = parts[1];  // Lake

It's not clear why you want to remove that exact part of the string, but here are some different ways of doing it for that exact string:

string sample = "Mountain View XX,Lake"

// option 1
string removed = sample.Remove(14, 3);

// option 2
string replaced = sample.Replace("XX,", String.Empty);

// option 3
string[] parts = sample.Split(',');
parts[0] = parts[0].Substring(0, 14);
string concatenated = String.Concat(parts);

If the XX part of the string is really something else, like a street number, then you would need something to determine how much of the string to remove. Here are some examples:

string sample = "Mountain View 123,Lake"

// option 1; remove digits followed by a comma
string replaced = Regex.Replace(sample, "\d+,", String.Empty);

// option 2; remove what's after the last space in the part before the comma
string[] parts = sample.Split(',');
parts[0] = parts[0].Substring(0, parts[0].LastIndexOf(" ") + 1);
string concatenated = String.Concat(parts);

You've left a lot out. Is XX always literally XX? Are you guaranteed that exact format or are you trusting user input? If you know you want all the beginning characters up until you hit a double capital letter combo you could do a very simple regex. I'd have to look it up since it has been years since I used those, but it would be super simple.

This does the trick. It does include the space before the two XX's. I am assuming the XX's can be any capital letters.

    Regex reg;
    reg = new Regex(".{1,}(?=[A-Z]{2})");
    var output = reg.Match("Mountain View XX, Lake");
    string text = output.Value;

You can test it out here: http://www.regexplanet.com/advanced/dotnet/index.html and learn more about regular expressions here: http://www.regular-expressions.info/tutorial.html

I would suggest you to go with:

string sample = "Mountain View XX,Lake";
Console.WriteLine(sample.Split(',')[1]);// Lake
Console.WriteLine(sample.Remove(sample.IndexOf("XX,")).Trim()); // Mountain View

Demo: http://ideone.com/RizzzC

I would maybe do something like this:

public static string[] MyCustomSplit(string input, List<string> reservedWords)
{
    List<string> outputLines = new List<string>();

    string[] lines = input.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

    foreach (string line in lines)
    {
        if (!string.IsNullOrWhiteSpace(line))
        {
            string[] parts = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            List<string> lineParts = new List<string>();

            foreach (string part in parts)
            {
                if (!reservedWords.Contains(part))
                {
                    lineParts.Add(part);
                }
            }

            outputLines.Add(string.Join(" ", lineParts.ToArray()));
        }
    }

    return outputLines.ToArray();
}

and then

string sample = "Mountain View XX,Lake";
List<string> reservedWords = new List<string>() { "XX" };
string[] test = MyCustomSplit(sample, reservedWords);

which results with:

string[0] = Mountain View
string[1] = Lake

Or something like this:

public static string[] MyCustomSplitAndCleanup(string input)
{
    List<string> outputLines = new List<string>();

    string[] lines = input.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

    foreach (string line in lines)
    {
        if (!string.IsNullOrWhiteSpace(line))
        {
            string[] parts = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            List<string> lineParts = new List<string>();

            for (int index = 0; index < parts.Length; index++ )
            {
                string part = parts[index];

                int numericValue = 0;

                bool validPart = true;

                if (int.TryParse(part, out numericValue))
                {
                    if (index == 0 || index == parts.Length - 1)
                    {
                        validPart = false;
                    }
                }

                if (validPart)
                {
                    lineParts.Add(part);
                }
            }

            outputLines.Add(string.Join(" ", lineParts.ToArray()));
        }
    }

    return outputLines.ToArray();
}

which covers this:

string sample1 = "Mountain View 32,Lake";
string sample2 = "17 Park place,Something";

string[] test1 = MyCustomSplitAndCleanup(sample1);
string[] test2 = MyCustomSplitAndCleanup(sample2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM