AFF
AFF

Reputation: 117

String Replacement C#

Hope you can give me some light on this:

I have this var

string TestString = "KESRNAN FOREST S BV";

I want to replace the S that is alone, so I tried with the following

public static string FixStreetName(string streetName)
    {
        string result = "";
        string stringToCheck = streetName.ToUpper();
    //   result = stringToCheck.Replace(StreetDirection(stringToCheck), "").Replace(StreetType(stringToCheck),"").Trim();

        result = stringToCheck.Replace("S", "").Replace("BV", "").Trim();

        return result;
    }

But this is replacing all S on that string. any ideas?

Upvotes: 0

Views: 136

Answers (5)

Masoud Mohammadi
Masoud Mohammadi

Reputation: 1739

Another way of doing what you want:

using System;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string testString = "S KESRNAN S FOREST BV S";
            // deleting S in middle of string
            for (int i = 1; i < testString.Length-1; i++)
            {
                if (testString[i]=='S'&&testString[i-1]==' '&&testString[i+1]==' ')
                    testString=testString.Remove(i,2);
            }
            // deleting S in the begining of string
            if (testString.StartsWith("S "))
                testString = testString.Remove(0, 2);
            // deleting S at the end of string
            if (testString.EndsWith(" S"))
                testString = testString.Remove(testString.Length-2, 2);
            Console.WriteLine(testString);
        }
    }
}

Upvotes: 0

Ali Vojdanian
Ali Vojdanian

Reputation: 2111

As you can see alone S is before a space " ". In the other word have this string "S " which want to replace it.

Try this :

        string TestString = "KESRNAN FOREST S BV";
        string replacement = TestString.Replace("S ", "");

Upvotes: 0

dovid
dovid

Reputation: 6452

Using Regex:

string input = "S KESRNAN FOREST S BV S";
string result = Regex.Replace(input, @"\b(S)", "");

Upvotes: 0

Tamim Al Manaseer
Tamim Al Manaseer

Reputation: 3724

Use regular expressions,

\b

denotes word boundaries. here is an example on C# Pad

string x = "KESRNAN FOREST S BV";

var result = System.Text.RegularExpressions.Regex.Replace(x, @"\bS\b", "");

Console.WriteLine(result);

Upvotes: 3

If you can easily identify certain "delimiter" characters, one possibility is to 1. split your input string into several parts using string.Split; then 2. pick the parts that you want, and finally 3. "glue" them back together using string.Join:

var partsToExclude = new string[] { "S", "BV" };

/* 1. */ var parts = stringToCheck.Split(' ');
/* 2. */ var selectedParts = parts.Where(part => !partsToExclude.Contains(part));
/* 3. */ return string.Join(" ", selectedParts.ToArray());

Upvotes: 1

Related Questions