string.replace() not working with xml string - c#

I have read all similar questions and acted accordingly. But still can't figure out what's wrong with my code.
This is my code, super simple. (I know this isn't valid XML. It's just for the example).
string replacement = "TimeSheetsReplaced";
string word = "TimeSheets";
string result = "<?xml version=\"1.0\" encoding=\"utf-16\"?><DisplayName>Timesheets</DisplayName>";
result = result.Replace("<DisplayName>" + word + "</DisplayName>", "<DisplayName>" + replacement + "</DisplayName>");
The result string remains unplaced. What am I doing wrong??

TimeSheets != Timesheets
Casing does not match

It's because your string contains Timesheets, but you're lokoing for TimeSheets (with a capital S).

In your word TimeSheets has big S, in string small s

Related

String concatenation using String interpolation

I've something like below.
var amount = "$1,000.99";
var formattedamount = string.Format("{0}{1}{0}", "\"", amount);
How can I achieve same using String interpolation?
I tried like below
var formattedamount1 = $"\"{amount}\"";
Is there any better way of doing this using string interpolation?
Update
Is there any better way of doing this using string interpolation
No, this is just string interpolation, you cant make the following any shorter and more readable really
var formattedamount1 = $"\"{amount}\"";
Original answer
$ - string interpolation (C# Reference)
To include a brace, "{" or "}", in the text produced by an
interpolated string, use two braces, "{{" or "}}". For more
information, see Escaping Braces.
Quotes are just escaped as normal
Example
string name = "Horace";
int age = 34;
Console.WriteLine($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
Output
He asked, "Is your name Horace?", but didn't wait for a reply :-{
Horace is 34 years old.
Same thing you can achieve by doing:
var formattedamount1 = $"\"{amount}\"";
OR
var formattedamount1 = $#"""{amount}""";
It's basically allowing you to write string.Format(), but instead of using one string with "placeholders"({0}, {1}, .. {N}), you are directly writing/using your variable inside string.
Please read more about String Interpolation (DotNetPerls), $ - string interpolation to fully understand whats going on.
Just to give one more option, if you want to make sure you use the same quote at both the start and the end, you could use a separate variable for that:
string quote = "\"";
string amount = "$1,000.99";
string formattedAmount = $"{quote}{amount}{quote}";
I'm not sure I'd bother with that personally, but it's another option to consider.

How to get second value via c# StartsWith() method

string text = "Today is a good day for help. **David Diaz He went to school. **David Diaz like apple. ";
How to get how many times the text **David Diaz occurs in the string text?
UPDATED MY QUESTION
By using StartWhith you can check if the string starts whit ** if it is take the first two words of the string whits will represent the name
string text = "**David Diaz He went to school.";
if (text.StartsWith("**"))
{
var names = text.Split(' ')
.Take(2)
.ToArray();
var fullName = names[0] + " " + names[1];
}
UPDATE
As you said in the commend you want to look how many David Diaz occurs in one string, you can use regex for that.
string text = "Today is a good day for help. **David Diaz He went to school. **David Diaz like apple. ";
int matches = Regex.Matches(
text,
#"(?:\S+\s)?\S*David Diaz\S*(?:\s\S+)?",
RegexOptions.IgnoreCase
).Count;
var text = "Today is a good day for help. **David Diaz He went to school. **David Diaz like apple. ";
var pos = 0;
var num = 0;
var search = "**David Diaz";
while ((pos = text.IndexOf(search, pos)) > -1)
{
num ++;
pos += search.Length;
}
Console.WriteLine(num);
you can try out this in dotnetfiddle
Updated Answer:
It sounds like you want to find the number of times a substring exists in your text. For that, you'll want to use RegEx.Matches, as explained in this answer: https://stackoverflow.com/a/3016577/682840
or LINQ, as explained in this answer: https://stackoverflow.com/a/541994/682840
Original Answer:
.StartsWith returns true/false if the string begins with the search string you provide. If you're wanting to know where a substring exists within your text, you'll need to use .IndexOf or a Regular Expression for more advanced scenarios.
IndexOf will return the location in the text where your provided search string starts (or -1 if it isn't found).

Issue with forming a string with double quotes

I want to form a string as <repeat><daily dayFrequency="10" /></repeat>
Wherein the value in "" comes from a textboxe.g in above string 10. I formed the string in C# as
#"<repeat><daily dayFrequency=""+ txt_daily.Text + "" /></repeat>" but i get the output as
<repeat><daily dayFrequency="+ txt_daily.Text+ " /></repeat>. How to form a string which includes the input from a textbox and also double quotes to be included in that string.
To insert the value of one string inside another you could consider string.Format:
string.Format("foo {0} bar", txt_daily.Text)
This is more readable than string concatenation.
However I would strongly advise against building the XML string yourself. With your code if the user enters text containing a < symbol it will result in invalid XML.
Create the XML using an XML library.
Related
How can I build XML in C#?
Escape it with \ Back slash. putting # in front wont do it for you
string str = "<repeat><daily dayFrequency=\"\"+ txt_daily.Text + \"\" /></repeat>";
Console.Write(str);
Output would be:
<repeat><daily dayFrequency=""+ txt_daily.Text + "" /></repeat>
You could do it like this:
var str = String.Format(#"<repeat><daily dayFrequency="{0}" /></repeat>",
txt_daily.Text);
But it would be best to have an object that mapped to this format, and serialize it to xml
string test = #"<repeat><daily dayFrequency=" + "\"" + txt_daily.Text + "\"" + "/></repeat>";

Extracting string that is present in one string and not other

I have two strings:
string strone="what is your name?"
string strtwo="what is your name? what is your school name?"
Any of the strings could be greater here. What I need is to extract string from strtwo which is not in strone.
What I have tried is this:
IEnumerable<string> str=strtwo.Except(strone); //(returns only first character ie w)
I tried converting both strone and strtwo to string arrays but looping through each string one by one won't provide solution as strone may contain other characters in between.
What i require is to extract the entire string sequentially in strtwo that is not in strone.
you can try to extract the text from the second string in this fashion
string diff = strtwo.Replace(strone,"");
This should output you " what is your school name?" which is what you are looking out for else please do update the question with other example/cases.
The simplest way is using Replace:
string strone="what is your name?";
string strtwo="what is your name? what is your school name?";
string finalStr = strtwo.Replace(strone, "");
If your looking for something that compares more than just the First part of the strings and shows the diff on the end then have a look at the Diff Implementation, but basically your looking for This Algorithm
However if you are just looking for the difference on the end of a string look at #dasblinkenlight solution
string strone="what is your name?"
string strtwo="what is your name? what is your school name?"
string extractedString = strtwo.Replace(strone, "");
why not looking at the result of
strtwo.Split(new String[]{strone}, StringSplitOptions.RemoveEmptyEntries)
?

c# parsing xml with and apostrophe throws exception

I am parsing an xml file and am running into an issue when trying find a node that has an apostrophe in it. When item name does not have this everything works fine. I have tried replacing the apostrophe with different escape chars but am not having much luck
string s = "/itemDB/item[#name='" + itemName + "']";
// Things i have tried that did not work
// s.Replace("'", "''");
// .Replace("'", "\'");
XmlNode parent = root.SelectSingleNode(s);
I always receive an XPathException. What is the proper way to do this. Thanks
For apostophe replace it with &apos;
You can do it Like this:
XmlDocument root = new XmlDocument();
root.LoadXml(#"<itemDB><item name=""abc'def""/></itemDB>");
XmlNode node = root.SelectSingleNode(#"itemDB/item[#name=""abc'def""]");
Note the verbatim string literal '#' and the double quotes.
Your code would then look like this and there is no need to replace anything:
var itemName = #"abc'def";
string s = #"/itemDB/item[#name=""" + itemName + #"""]";

Categories

Resources