Add String into existing String whenever specific characters found - c#

I want to add a specific String into an existing String whenever the existing String contains one of the following characters: =, +, -, * or /.
For example, I want to add the String "test" into this existing String:
"=ABC+DEF"
Resulting String should be: "=testABC+testDEF"
My first version looks like this and I quess it works but code is ugly
string originalFormula;
string newFormula1 = originalFormula.Replace("=", "=test");
string newFormula2 = newFormula1.Replace("+", "+test");
string newFormula3 = newFormula2 .Replace("-", "-test");
string newFormula4 = newFormula3 .Replace("*", "*test");
string newFormula5 = newFormula4 .Replace("/", "/test");
Is there some shorter way to achive it ?

If you want your code a bit more elegant, go with Regex.
using System.Text.RegularExpressions;
string originalFormula = ...;
var replacedString = Regex.Replace(myString, "[-+*/=]", "$&test");
For better understanding:
[-+*/=] groups the charackters you want to check the string for. $&test Replaces the found charackter with its match ($&) and adds test to it.

If your problem is that your code looks ugly maybe you could rewrite it to use a list rather...
List<char> characters = new List<char> { '+', '-', '*', '/' };
foreach (var c in characters)
{
string newValue = String.Format("{0}{1}", c, somethingElse);
if (originalForumla.Contains(c);
{
newForumla = originalFormula.Replace(c, newValue);
}
}

Related

Find and move unknown word between particular characters in the string C#

I'm trying to find and move unknown word between particular characters in the string in C#.
Example:
// this is a string from the file
begining of the string - " TASK PERS partdata pd_Test_05:=["Call_Test_05","Test_05","T_ROB1",1,0,"",""];" - end of the string.
// I insert that string inside the string[] lines.
// I need to found and seperate word "Test_05" from that string.
It looks like you might be able to do something like this:
List<string> test = yourString.Split(',').ToList<string>();
string finalProduct = test[1];
At this point, your string would look like "Test_05". Just replace the quotation marks with C#'s replace or Regex replace them.
Its hard to know how to give an answer, we dont know what makes Test_05 the particular target.
As a general guide you can either use Regular expressions if the target string matches a pattern. You might find this site useful http://regexstorm.net/
Or you can use string operations like IndexOf (search for a given string in a string), Substring (slice out a piece of a string), Replace,...
Thanks GMR516.
I finished with 'Trim.
string[] lines = File.ReadAllLines("testFile.mod");
List<string> test = lines[0].Split(',').ToList<string>();
string finalProduct = test[1].Remove(1, 0);
Console.WriteLine($"Before trim: {finalProduct}");
char[] charsToTrim = { '*', ' ', '\'', '"' };
// Trim method can remove any characters from specified string
string result = finalProduct.Trim(charsToTrim);
Console.WriteLine($"After Trim: {result}");

Replace character with any possible string c#

Lets say i have string like this Test%Test and i have stored strings like this:
Test123Test
TestTTTTest
Test153jhdsTest
123Test
TEST123
So what i want is when i type in textbox Test it would filter me everything with Test in itselft and that will get me all strings which is easy, but i want to type in Test%Test and it needs to filter me everything that has Test[anything]Test in itself (so result would be first, second and third string). How can i do it?
a simple solution using a regex is:
string[] values = new string[] { "Test123Test",
"TestTTTTest",
"Test153jhdsTest",
"123Test",
"TEST123" };
string searchQuery = "Test%Test";
string regex = Regex.Escape(searchQuery).Replace("%", ".*?");
string[] filteredValues = values.Where(str => Regex.IsMatch(str, regex)).ToArray();
Or for a single match:
string value = "Test123Test";
string searchQuery = "Test%Test";
string regex = Regex.Escape(searchQuery).Replace("%", ".*?");
if ( Regex.IsMatch(value, regex) )
{
// do something with the match...
}
We replace % with a regular expression (. = any character, * = zero or more times, ? = lazy quantifier). You can learn more about regular expressions here

Regex replace special characters defind by client

I need a c# function which will replace all special characters customized by the client from a string Example
string value1 = #"‹¥ó׬¶ÝÆ";
string input1 = #"Thi¥s is\123a strÆing";
string output1 = Regex.Replace(input1, value1, "");
I want have a result like this : output1 =Thi s is\123a str ing
Why do you need regex? This is more efficient, concise also readable:
string result = string.Concat(input1.Except(value1));
If you don't want to remove but replace them with a different string you can still use a similar(but not as efficient) approach:
string replacement = "[foo]";
var newChars = input1.SelectMany(c => value1.Contains(c) ? replacement : c.ToString());
string result = string.Concat( newChars ); // Thi[foo]s is\123a str[foo]ing
Someone asked for a regex?
string value1 = #"^\-[]‹¥ó׬¶ÝÆ";
string input1 = #"T-^\hi¥s is\123a strÆing";
// Handles ]^-\ by escaping them
string value1b = Regex.Replace(value1, #"([\]\^\-\\])", #"\$1");
// Creates a [...] regex and uses it
string input1b = Regex.Replace(input1, "[" + value1b + "]", " ");
The basic idea is to use a [...] regex. But first you have to escape some characters that have special meaning inside a [...]. They should be ]^-\ Note that you don't need to escape the [
note that this solution isn't compatible with non-BMP unicode characters (characters that fill-up two char)
A solution that is compatible with them is more complex, but for normal use it shouldn't be a problem.

replacing characters in a single field of a comma-separated list

I have string in my c# code
a,b,c,d,"e,f",g,h
I want to replace "e,f" with "e f" i.e. ',' which is inside inverted comma should be replaced by space.
I tried using string.split but it is not working for me.
OK, I can't be bothered to think of a regex approach so I am going to offer an old fashioned loop approach which will work:
string DoReplace(string input)
{
bool isInner = false;//flag to detect if we are in the inner string or not
string result = "";//result to return
foreach(char c in input)//loop each character in the input string
{
if(isInner && c == ',')//if we are in an inner string and it is a comma, append space
result += " ";
else//otherwise append the character
result += c;
if(c == '"')//if we have hit an inner quote, toggle the flag
isInner = !isInner;
}
return result;
}
NOTE: This solution assumes that there can only be one level of inner quotes, for example you cannot have "a,b,c,"d,e,"f,g",h",i,j" - because that's just plain madness!
For the scenario where you only need to match one pair of letters, the following regex will work:
string source = "a,b,c,d,\"e,f\",g,h";
string pattern = "\"([\\w]),([\\w])\"";
string replace = "\"$1 $2\"";
string result = Regex.Replace(source, pattern, replace);
Console.WriteLine(result); // a,b,c,d,"e f",g,h
Breaking apart the pattern, it is matching any instance where there is a "X,X" sequence where X is any letter, and is replacing it with the very same sequence, with a space in between the letters instead of a comma.
You could easily extend this if you needed to to have it match more than one letter, etc, as needed.
For the case where you can have multiple letters separated by commas within quotes that need to be replaced, the following can do it for you. Sample text is a,b,c,d,"e,f,a",g,h:
string source = "a,b,c,d,\"e,f,a\",g,h";
string pattern = "\"([ ,\\w]+),([ ,\\w]+)\"";
string replace = "\"$1 $2\"";
string result = source;
while (Regex.IsMatch(result, pattern)) {
result = Regex.Replace(result, pattern, replace);
}
Console.WriteLine(result); // a,b,c,d,"e f a",g,h
This does something similar compared to the first one, but just removes any comma that is sandwiched by letters surrounded by quotes, and repeats it until all cases are removed.
Here's a somewhat fragile but simple solution:
string.Join("\"", line.Split('"').Select((s, i) => i % 2 == 0 ? s : s.Replace(",", " ")))
It's fragile because it doesn't handle flavors of CSV that escape double-quotes inside double-quotes.
Use the following code:
string str = "a,b,c,d,\"e,f\",g,h";
string[] str2 = str.Split('\"');
var str3 = str2.Select(p => ((p.StartsWith(",") || p.EndsWith(",")) ? p : p.Replace(',', ' '))).ToList();
str = string.Join("", str3);
Use Split() and Join():
string input = "a,b,c,d,\"e,f\",g,h";
string[] pieces = input.Split('"');
for ( int i = 1; i < pieces.Length; i += 2 )
{
pieces[i] = string.Join(" ", pieces[i].Split(','));
}
string output = string.Join("\"", pieces);
Console.WriteLine(output);
// output: a,b,c,d,"e f",g,h

String "de-concatenation"

I have two strings like this
string s = "abcdef";
string t = "def";
I would like to remove t from s. Can I do this like this?
s = s - t?
EDIT
I will have two strings s and t, t will be an ending substring of s. I want to remove t from s.
No, but you can do this:
var newStr = "abcdef".Replace("def", "");
Per your comments, if you want to only remove the trailing pattern you can use a Regex:
var newStr = Regex.Replace("defdefdef", "(def)$", "");
The '$' will anchor to the end of the string, so it will only remove the final 'def'
Turning this into an extension method:
public static String ReplaceEnd(this string input, string subStr, string replace = "")
{
//Per Alexei Levenkov's comments, the string should
// be escaped in order to avoid accidental injection
// of special characters into the Regex pattern
var escaped = Regex.Escape(subStr);
var pattern = String.Format("({0})$", escaped);
return Regex.Replace(input, pattern, replace);
}
Using this method with your code above would become:
string s = "abcdef";
string t = "def";
s = s.ReplaceEnd(t); // Ta Da!
Like this:
if (s.EndsWith(t))
{
s = s.Substring(0, s.LastIndexOf(t));
}
s = s.Substring(0, s.Length - t.Length)
Substring takes two arguments: start and length. You want to take things from the start of abcdef, that's index 0, and you want to take all the characters minus the characters from t, which is the difference of length of the two strings.
This assumes the OP's contract of "t will be an ending substring of s". If in fact this precondition is not guaranteed, it needs if (s.EndsWith(t)) around it.

Categories

Resources