Cutting a String before a special character everytime in C# - c#

I have strings that all have different lengths.
e.g.
str1 = "This is new job ----First Message----- This is reopened ";
str2 = "Start Process ----First Message----- Is this process closed? <br/> no ----First Message-----";
Now these string shall always have the "----First Message-----" in it.
What I need is to trim or split the string in such a way that I only get the part left of the FIRST TIME the "----First Message-----" occurs.
So in case of str1 result should be "This is new job "
For str2 it should be "Start Process "
How can this be done in C#?

string stringStart = str1.Substring(0, str1.IndexOf("----First Message-----"));

String result = input.Substring(0, input.IndexOf('---FirstMessage-----'));
actually, for teaching purposes...
private String GetTextUpToFirstMessage( String input ){
const string token = "---FirstMessage-----";
return input.Substring(0, input.IndexOf(token));
}

This sounds like a job for REGULAR EXPRESSIONS!!!!
try the following code. don't forget to include the using System.Text.RegularExpressions; statement at the top.
Regex regex = new Regex(#"^(.*)----FirstMessage----$");
string myString = regex.Match(str1).Value;

Related

C# Finding numerical value from specific string

I have a string of varying length that I am trying to retrieve a number from. The format of the string is always:
"some text lines
FC = 1234
more text here
and so on"
So I know the string of numbers comes after "FC = ", and I know it finishes at the next \n. How can I return this number (which will vary in size) into a new string?
Try the following code snippet:
var str = "some text lines \nFC = 1234\n more text here and so on";
Console.WriteLine(Regex.Match(str, #"\d+\.*\d*").Value);
Thanks to all. Think I managed to find a way with Regex, based on ScareCrow's suggestion:
string rgSearch = searchString + #"\d+\.*\d*";
FC = Regex.Match(diagnostics, rgSearch).Value;
FC = FC.Replace(searchString, ""); //Leaves the number only

Remove part of a string between an start and end

Code first:
string myString = "<at>onePossibleName</at> some question here regarding <at>disPossibleName</at>"
// some code to handle myString and save it in myEditedString
Console.WriteLine(myEditedString);
//output now is: some question here regarding <at>disPossibleName</at>
I want to remove <at>onePossibleName</at> from myString. The string onePossibleName and disPossbileName could be any other string.
So far I am working with
string myEditedString = string.Join(" ", myString.Split(' ').Skip(1));
The problem here would be that if onePossibleName becomes one Possible Name.
Same goes for the try with myString.Remove(startIndex, count) - this is not the solution.
There will be different method depending on what you want, you can go with a IndexOf and a SubString, regex would be a solution too.
// SubString and IndexOf method
// Usefull if you don't care of the word in the at tag, and you want to remove the first at tag
if (myString.Contains("</at>"))
{
var myEditedString = myString.Substring(myString.IndexOf("</at>") + 5);
}
// Regex method
var stringToRemove = "onePossibleName";
var rgx = new Regex($"<at>{stringToRemove}</at>");
var myEditedString = rgx.Replace(myString, string.Empty, 1); // The 1 precise that only the first occurrence will be replaced
You could use this generic regular expression.
var myString = "<at>onePossibleName</at> some question here regarding <at>disPossibleName</at>";
var rg = new Regex(#"<at>(.*?)<\/at>");
var result = rg.Replace(myString, "").Trim();
This would remove all 'at' tags and the content between. The Trim() call is to remove any white space at the beginning/end of the string after the replacement.
string myString = "<at>onePossibleName</at> some question here regarding <at>disPossibleName</at>"
int sFrom = myString.IndexOf("<at>") + "<at>".Length;
int sTo = myString.IndexOf("</at>");
string myEditedString = myString.SubString(sFrom, sFrom - sTo);
Console.WriteLine(myEditedString);
//output now is: some question here regarding <at>disPossibleName</at>

string replace but only if not contained within 2 other strings

Imagine I have a string like:
xxxstrvvv string xxxstringvvv str I am string for testing.
I want to find and replace all instances of str with xxxstrvvv that are not already contained in a xxxvvv.
so the result would be:
xxxstrvvv xxxstrvvving xxxstringvvv xxxstrvvv I am xxxstrvvving for testing
Anyone know an easy way to do this?
Edit: I want to add another situation to clarify.
xxxabcstrefgvvv
it should NOT replace this because the str is contained in xxxvvv
I suggest using regular expression with negative looking ahead and behind:
string source = "xxxstrvvv string xxxstringvvv str I am string for testing.";
string result = Regex.Replace(source, #"(?<!xxx)str(?!vvv)", "xxxstrvvv");
Edit: Same method, but a bit different pattern for the edited question:
string result = Regex.Replace(
source,
#"(?<!xxx[a-zA-Z]*)str(?![a-zA-Z]*vvv)", "xxxstrvvv");
Outcomes:
source = "xxxstrvvv string xxxstringvvv str I am string for testing.":
xxxstrvvv xxxstrvvving xxxstringvvv xxxstrvvv I am xxxstrvvving for testing.
source = "xxxabcstrefgvvv":
xxxabcstrefgvvv
Ok, I agreed with the answer of Dmitry Bychenko about Regular Expressions.
But, if your request is limited to the requirement on your answer we can use this code:
string val = "xxxstrvvv string xxxstringvvv str I am string for testing.";
val = val.Replace("xxxstringvvv", "str");
val = val.Replace("str","xxxstringvvv");
I'd go with the regex, but if you want to use replaces, this would work, if you don't have "xxxxxxstrvvvvvv" in your initial string and want to keep them that way:
string findString = "str";
string addBefore = "xxx";
string addAfter = "xxx";
string myString = "xxxstrvvv string xxxstringvvv str I am string for testing.";
myString = myString.Replace(findString, addBefore+findString+addAfter);
myString = myString.Replace(addBefore+addBefore+findString+addAfter+addAfter, addBefore+findString+addAfter);
Yes; it is ugly. I just basically do that in Notepad++ all the time with ctrl-H.
I have written a script in Python. I think you would be able to convert it to C#.
one_line = 'xxxstrvvv string xxxstringvvv str I am string for testing'
final_str = ""
arry_len = one_line.split(" ")
for ch in arry_len:
if 'str' in ch:
if not 'xxxstrvvv' in ch:
ch = ch.replace("str","xxxstrvvv")
final_str = final_str + " " + ch
print final_str

Replacing 2 new lines and tab with string using regular expression

This seems really simple, but I have a string that I want to replace a string with a tab and 2 new lines and it isn't working.
string newString = "\tMyVariable : Bool\n\t\nEND_VAR";
string pattern = "\n\t\nEND_VAR";
string original = "VAR_GLOBAL\n\t\nEND_VAR\n";
string updatedString = Regex.Replace(original,pattern,newString);
updatedString never gets updated, it remains at "VAR_GLOBAL\n\t\nEND_VAR\n", where it should be "VAR_GLOBAL\tMyVariable : Bool\n\t\nEND_VAR\n". I'm not sure why it won't change.
While Regex might not be the best suited for such scenario, please find below a sample code which will suit your needs (Regex test).
string newString = "\tMyVariable : Bool\n\t\nEND_VAR";
string pattern = "\\n\\t\\nEND_VAR";
string original = "VAR_GLOBAL\n\t\nEND_VAR\n";
string updatedString = Regex.Replace(original,pattern,newString);
The other (maybe simplier) option would be to do a straight replace like in:
string newString = "\tMyVariable : Bool\n\t\nEND_VAR";
string updatedString = newString.Replace("\n\t\n", "\t");

How to insert newline in string literal?

In .NET I can provide both \r or \n string literals, but there is a way to insert
something like "new line" special character like Environment.NewLine static property?
Well, simple options are:
string.Format:
string x = string.Format("first line{0}second line", Environment.NewLine);
String concatenation:
string x = "first line" + Environment.NewLine + "second line";
String interpolation (in C#6 and above):
string x = $"first line{Environment.NewLine}second line";
You could also use \n everywhere, and replace:
string x = "first line\nsecond line\nthird line".Replace("\n",
Environment.NewLine);
Note that you can't make this a string constant, because the value of Environment.NewLine will only be available at execution time.
If you want a const string that contains Environment.NewLine in it you can do something like this:
const string stringWithNewLine =
#"first line
second line
third line";
EDIT
Since this is in a const string it is done in compile time therefore it is the compiler's interpretation of a newline. I can't seem to find a reference explaining this behavior but, I can prove it works as intended. I compiled this code on both Windows and Ubuntu (with Mono) then disassembled and these are the results:
As you can see, in Windows newlines are interpreted as \r\n and on Ubuntu as \n
var sb = new StringBuilder();
sb.Append(first);
sb.AppendLine(); // which is equal to Append(Environment.NewLine);
sb.Append(second);
return sb.ToString();
One more way of convenient placement of Environment.NewLine in format string.
The idea is to create string extension method that formats string as usual but also replaces {nl} in text with Environment.NewLine
Usage
" X={0} {nl} Y={1}{nl} X+Y={2}".FormatIt(1, 2, 1+2);
gives:
X=1
Y=2
X+Y=3
Code
///<summary>
/// Use "string".FormatIt(...) instead of string.Format("string, ...)
/// Use {nl} in text to insert Environment.NewLine
///</summary>
///<exception cref="ArgumentNullException">If format is null</exception>
[StringFormatMethod("format")]
public static string FormatIt(this string format, params object[] args)
{
if (format == null) throw new ArgumentNullException("format");
return string.Format(format.Replace("{nl}", Environment.NewLine), args);
}
Note
If you want ReSharper to highlight your parameters, add attribute to the method above
[StringFormatMethod("format")]
This implementation is obviously less efficient than just String.Format
Maybe one, who interested in this question would be interested in the next question too:
Named string formatting in C#
string myText =
#"<div class=""firstLine""></div>
<div class=""secondLine""></div>
<div class=""thirdLine""></div>";
that's not it:
string myText =
#"<div class=\"firstLine\"></div>
<div class=\"secondLine\"></div>
<div class=\"thirdLine\"></div>";
If you really want the New Line string as a constant, then you can do this:
public readonly string myVar = Environment.NewLine;
The user of the readonly keyword in C# means that this variable can only be assigned to once. You can find the documentation on it here. It allows the declaration of a constant variable whose value isn't known until execution time.
static class MyClass
{
public const string NewLine="\n";
}
string x = "first line" + MyClass.NewLine + "second line"
newer .net versions allow you to use $ in front of the literal which allows you to use variables inside like follows:
var x = $"Line 1{Environment.NewLine}Line 2{Environment.NewLine}Line 3";
If you are working with Web application you can try this.
StringBuilder sb = new StringBuilder();
sb.AppendLine("Some text with line one");
sb.AppendLine("Some mpre text with line two");
MyLabel.Text = sb.ToString().Replace(Environment.NewLine, "<br />")
If I understand the question: Couple "\r\n" to get that new line below in a textbox. My example worked -
string s1 = comboBox1.Text; // s1 is the variable assigned to box 1, etc.
string s2 = comboBox2.Text;
string both = s1 + "\r\n" + s2;
textBox1.Text = both;
A typical answer could be s1
s2 in the text box using defined type style.
I like more the "pythonic way"
List<string> lines = new List<string> {
"line1",
"line2",
String.Format("{0} - {1} | {2}",
someVar,
othervar,
thirdVar
)
};
if(foo)
lines.Add("line3");
return String.Join(Environment.NewLine, lines);
Here, Environment.NewLine doesn't worked.
I put a "<br/>" in a string and worked.
Ex:
ltrYourLiteral.Text = "First line.<br/>Second Line.";

Categories