How to remove all occurrence with a specific pattern? [duplicate] - c#

This question already has an answer here:
C# Remove a letter that trails a number from multiple instances in a string whether with Regex by another method
(1 answer)
Closed 4 years ago.
Suppose I have a file like this:
EN;05;UK;55;EN;66;US;87;US;89;EN;66;UK;87;
I want remove all the EN occurrence, so the final string should be:
UK;55;US;87;US;89;UK;87;
I can remove the EN using string.Replace("EN", "") but how to remove also the number?

I will propose an alternative not using RegEx. This will work if the number following the abbreviation is more than two characters.
public static string RemoveDataPoints(this string data, string indentifier)
{
var temp = "";
var fields = data.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
for (int i=0; i<fields.Length; i=i+2)
{
if (!fields[i].Equals(indentifier))
{
temp += String.Format("{0};{1};", fields[i], fields[i + 1]);
}
}
return temp;
}
Then call:
var output = "EN;05;UK;55;EN;66;US;87;US;89;EN;66;UK;87;".RemoveDataPoints("EN");

You could make use of a regular expression:
string output = Regex.Replace(input, "EN\\;\\d{2}\\;", "");
where input is your string, EN;05;UK;55;EN;66;US;87;US;89;EN;66;UK;87;.

Related

c# find keywords in a string and remove it [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have got a list with keywords. And I coded a method that if a string contains keyword from list, the method must remove keyword from string. Here is the method:
private string RemoveFromList(string sentence)
{
var lists = new List<string>{ "ask-", "que-", "(app)", "(exe)", "(foo)" };
var control = lists.Any(sentence.Contains);
string result;
if (control)
{
var index = sentence.IndexOf(lists.FirstOrDefault(sentence.Contains)
?? throw new InvalidOperationException(), StringComparison.Ordinal);
result = index != -1 ? sentence.Remove(index) : sentence;
}
else
result = sentence;
return result;
}
var str = "ask- This is a sentence.";
Message.Box(RemoveFromList(str));
// It does not give to me: This is a sentence.
This method does not work properly. It does not remove the keyword from the string.
Using string.Replace is the simplest approach:
foreach (var word in lists)
{
sentence = sentence.Replace(word,"").Trim();
}
Although that will find the word in the middle of the string too. If you wanted to remove it only at the start you could use IndexOf check it's 0 and then take the string starting from word.Length using Substring. Or use StartsWith:
foreach (var word in lists)
{
if (sentence.StartsWith(word))
{
sentence = sentence.Substring(word.Length).Trim();
// break; // if only one
}
}
There are 2 options for you.
First of all the Remove usage is incorrect. You just want to remove the keyword. If u pass 1 argument to remove it will remove from that index till end. Pass the length of keyword as second arg to Remove.
s.Remove(index, len);
If string contains it than replace the occurrence of keyword with empty string
s.Replace("keyword", "");
Another option is you could create an extension since you already know what items to remove.
using System.Text.RegularExpressions;
public static string RemoveFromList(this string sentence)
{
new List<string>{ "ask-",
"que-",
"(app)",
"(exe)",
"(foo)" }.ForEach(name =>
{
sentence = Regex.Replace(sentence.Replace(name, string.Empty), " {2,}", " ");
});
return sentence;
}
Useage
var str = "ask- This is (app) a que- sentence.".RemoveFromList();
Note
I used Regex.Replace as it's possible you may have some blank spaces floating around after you remove the bad string/s, this helps ensure that doesn't happen.

Swear word filter in c# [duplicate]

This question already has answers here:
C# string replace does not actually replace the value in the string [duplicate]
(3 answers)
Closed 3 years ago.
I am trying to make a swear word filter in c#. I am using a string list and going through it and checking if the input contains a word from the list. But when i run the code, it does not filter anything.
I have tried to make it an array change it to a boolean but nothing seems to work.
private List<string> badWords = new List<string>();
public string FilterSwear(string text)
{
string filterd = text;
foreach (string badWord in badWords)
{
if (text.Contains(badWord))
{
int chars = badWord.Length;
string stars = "";
for (int i = 0; i < chars; i++)
{
stars += "*";
}
filterd.Replace(badWord, stars);
}
}
return filterd;
}
Try:
filterd = filterd.Replace(badWord, stars);
Replace doesn't replace in-place - it returns copy with replaced string and leaves original intact.

Process "\" in a string to "\\" for FilePath processing [duplicate]

This question already has answers here:
C# replace string in string
(7 answers)
Closed 4 years ago.
I have a function in where I want to convert a string value C:\samplec#programs\Converter to C:\\samplec#programs\\Converter Note the differences. This is my function:
private string FilePathProcessor(string path)
{
char[] oriCharArray = path.ToCharArray;
List<char> oriCharList = new List<char>;
List<char> newCharList = new List<char>;
foreach (char item in oriCharArray)
{
oriCharList.Add(item);
}
foreach (char items in oriCharList)
{
if ((items != "\\"))
{
newCharList.Add(items);
}
else
{
newCharList.Add(items);
newCharList.Add(items);
}
}
string result = string.Join(",", newCharList.ToArray());
return result;
}
Of course this function serves my needs. But, I wonder if there is already an existing function in .Net which will take care of it. I am just cleaning up my code and checking for simpler and faster solution. Not going to reinvent the wheel if there is already a way.
Use String.Replace()
string path = #"C:\samplec#programs\Converter";
string output = path.Replace("\\", #"\\");

how to get the following data from a string [duplicate]

This question already has answers here:
Get Substring - everything before certain char
(9 answers)
Closed 6 years ago.
I am using C#
I got a string which looks something like this :
myString = "User1:John&User2:Bob'More text"
I used
var parsed = HttpUtility.ParseQueryString(myString);
and then i use parsed["User1"] and parsed["User2"] to get the data.
My problem is that parsed["User2"] returns me not only the name but also everything that comes after it.
I thought maybe to then seperate by the char '
But i not sure how to do it since it has a specific behaviour in Visual studio.
I thought about something like this?
private static string seperateStringByChar(string text)
{
int indexOfChar = text.IndexOf(');
if (indexOfChar > 0)
{
return text.Substring(0, indexOfChar);
}
else
{
return "";
}
}
This worked for me as Wiktor suggested.
if (s.IndexOf("'") > -1) { return text.Substring(0, text.IndexOf("'")); } else { return string.Empty; }
A clean way of doing it is by splitting the string besides the index of the ' and then getting the substring.
var splittedText = text.Split('\'');
Then you can separate it further. e.g
var splittedText2 = splittedtText[0].Split('\&');
var User1 = splittedText2[0].Split(':')[1];
var User2 = splittedText2[1].Split(':')[1];
Let's sum up the splitting.
var users=myString.Split('\'');
var john = users.Split('&')[0].Split(':')[1];
var bob = users.Split('&')[1].Split(':')[1];

C# Multiple String Contains [duplicate]

This question already has answers here:
How to simplify an if condition having multiple OR cases [closed]
(5 answers)
Closed 6 years ago.
Basically I want to detect more than one string, current code example is
if (!str3.Contains("example1"))
{
continue;
}
How would I add " example1 ", " example2 " & " example3 "
You can use Linq if you want to test with a large list:
var excludes = new[] { "example1", "example2", "example3" };
//your loop here
{
if (!excludes.Any(x => str3.Contains(x)))
{
continue;
}
}
Personally, I prefer the way of looping because it solves the problem of manually expanding your code. For example...
public void MyMethod(string param)
{
var myList = new string[]
{
"example1",
"example2",
"example3"
};
foreach (var item in myList)
{
if (!param.Contains(item)) continue;
}
//Do something here
}
Basically, you're creating a collection of items you want to search for. Using that, you loop through them and compare them against the target string.
I don't know the full scope of the function so I can't exactly add more but this is already pretty basic.
If the strings follow a specific pattern, Regex is always a clean-looking option.
If the strings are "example1", "example2", etc., you could use this regex:
/example[0-9]+/g
Some C# to find the first and second match (source: http://www.dotnetperls.com/regex):
// Get first match.
Match match = Regex.Match(str3, #"example[0-9]+");
if (match.Success)
{
//matched one of the strings
}
// Get second match.
match = match.NextMatch();
if (match.Success)
{
//process second match
}

Categories