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("\\", #"\\");
Related
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.
This question already has answers here:
My regex is matching too much. How do I make it stop? [duplicate]
(5 answers)
What do 'lazy' and 'greedy' mean in the context of regular expressions?
(13 answers)
Closed 4 years ago.
This is probably a duplicate but I m too dense to make this work. I m trying to learn capture groups etc but I cant make this one work, I get the right matches but only the last digit gets matched.
class Program
{
static void Main(string[] args)
{
string testTxt = "sadsadas168.asdsad";
string asdf = "wrongwrong";
string abc = "abc.png";
string bsdf = "100";
string lolol = "155abx.text";
string another = "sasd199.ong100";
TryMatch(testTxt);
TryMatch(asdf);
TryMatch(abc);
TryMatch(bsdf);
TryMatch(lolol);
TryMatch(another);
Console.ReadLine();
}
private static void TryMatch(string txt)
{
var rgx = new Regex(#"\w*(?<t>\d+)\w*\..*");
var m = rgx.Match(txt);
if (m.Success)
{
int mainID = int.Parse(m.Groups["t"].Value);
Console.WriteLine(m.Groups["t"].Value);
}
else
{
Console.WriteLine("Did not match " + txt);
}
}
}
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;.
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];
This question already has answers here:
How to remove illegal characters from path and filenames?
(30 answers)
Closed 9 years ago.
I've wrote this little method to achieve the goal in the subj., however, is there more efficient (simpler) way of doing this? I hope this can help somebody who will search for this like I did.
var fileName = new System.Text.StringBuilder();
fileName.Append("*Bad/\ :, Filename,? ");
// get rid of invalid chars
while (fileName.ToString().IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) > -1)
{
fileName = fileName.Remove(fileName.ToString().IndexOfAny(System.IO.Path.GetInvalidFileNameChars()), 1);
}
?
I know this is a few years old but here is another solution for reference.
public string GetSafeFilename(string filename)
{
return string.Join("_", filename.Split(Path.GetInvalidFileNameChars()));
}
Try the following
public string MakeValidFileName(string name) {
var builder = new StringBuilder();
var invalid = System.IO.Path.GetInvalidFileNameChars();
foreach ( var cur in name ) {
if ( !invalid.Contains(cur) ) {
builder.Append(cur);
}
}
return builder.ToString();
}
A different approach that is compatible with .NET 4. See my comments above explaining the need.
public static string ScrubFileName(string value)
{
var sb = new StringBuilder(value);
foreach (char item in Path.GetInvalidFileNameChars())
{
sb.Replace(item.ToString(), "");
}
return sb.ToString();
}
If you look for "concise" when you say simple:
public string StripInvalidChars(string filename) {
return new String(
filename.Except(System.IO.Path.GetInvalidFileNameChars()).ToArray()
);
}
That said, I'd go with JaredPar's solution. It's probably easier to read (depending on taste, background), my gut feeling is that it is more efficient (although I'm not sure how efficient you have to be stripping that dozen of invalid chars from a limited length filename) and his use of a StringBuilder() seems to fit perfectly to your example.