How to escape quotes with string.replace - c#

Not sure my brain has completely started today...
I would need to escape defined quotation marks (" or ') in a string provided by the user, so depending on selected char the transformation should look like follows:
"I'm not so \"stupid\", am I?" => "I\\'m not so \"stupid\", am I?"
"I'm not so \"stupid\", am I?" => "I'm not so \\\"stupid\\\", am I?"
Trying to use string.Replace(string, string) drives me a little bit crazy, because it still refuses to perform the desired replacements (no additional backslashes are inserted to the result). And I still refuse to do it manually via loop ;)
Dictionary<Type, char> qString; // ...
valueStr = "I'm not so \"stupid\", am I?"; // Illustation only, in reality there is some user input used
// ...
string escFrom = qString[type].ToString(); // Make string from the quotation mark
string escTo = "\\" + escFrom; // Add the escape to it
valueStr.Replace(escFrom, escTo); // Try to replace it
Could you please help me with the mentioned startup completion?
Is there any obvious error I'm doing and not seeing?
Is there any hack like "safe" strings or any "culture" related stuff?

The Replace method doesn't change the string, you have to assign the result of the method call to a string.
You need to escape backslashes also, so it would be:
string escFrom = qString[type].ToString();
string escTo = "\\" + escFrom;
valueStr = valueStr.Replace("\\", "\\\\").Replace(escFrom, escTo);

you need to assign the result back:
valueStr=valueStr.Replace(escFrom, escTo);

If you just wand to replace characters, it could be done with the Replace method, where you would have to use its return value; however I second the comments above that the approach might not be suitable, of course depending on what you are finally trying to achieve.

Related

How to get data from each row of website (DownloadString) by after : char and stop till ; char

I use WebClient and DownloadString to get RAW text file into an string, and I would like to get the first words, like each thing before : char in to a string, AND also the stuff after : but before ; in other string. In this case I want word111 and floor271 in seperate string, and table123 and fan891 into an other string.
The text file looks like this:
word111:table123;
floor271:fan891;
I've tried to look around for days, because I use in my code the Contains method to see if the whole line of text sometimes matches, example word111:table123; if that exists in the raw text file, then the code continues. I looked at Split, IndexOf, and things like that but I don't understand if they can even achieve this goal, because I need them from every row/line, not just one.
WebClient HWIDReader = new WebClient();
string HWIDList = HWIDReader.DownloadString("/*the link would be here, can't share it*/");
if (HWIDList.Contains(usernameBox.Text + ":" + passwordBox.Text))
{
/* show other form because username and password did exist */
}
I expect the code wouldn't work with Split, because it can split the string by : and ; characters tho, but I don't want the usernames and passwords visible in the same string. IndexOf would delete before or after specified characters tho. (Maybe can use IndexOf to both ways? to remove from : till ; is that possible, and how?) Thank you in advance.
You can split the string based on the newline character.
string HWIDList = HWIDReader.DownloadString("/*the link would be here, can't share it*/");
string[] lines = HWIDList.Split('\n');
// NOTE: Should create a hash from the password and compare to saved password hashes
// so that nobody knows what the users' passwords are
string userInput = string.Format("{0}:{1};", usernameBox.Text, passwordBox.Text);
foreach (string pair in lines)
{
if (pair != userInput)
continue;
// found match: do stuff
}

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 place double quotes inside the double quotes of string.IndexOf() function?

I have a String I want to get the index of the "id:" i.e the id along with the double quotes.
How I am supposed to do so inside C# string.IndexOf function?
This will get the index of the string you want:
var idx = input.IndexOf("\"id:\"");
if you wanted to pull it out you'd do something like this maybe:
var idx = input.IndexOf("\"id:\"");
var val = input.Substring(idx, len);
where len is either a statically known length or also calculated by another IndexOf statement.
Honestly, this could also be done with a Regex, and if an example were available a Regex may be the right approach because you're presumably trying to get the actual value here and it's presumably JSON you're reading.
" is an escape sequence
If you want to use a double quotation mark in your string, you should use \" instead.
For example;
int index = yourstring.IndexOf("\"id:\"");
Remember, String.IndexOf method gets zero-based index of the first occurrence of the your string.
This is a simple approach: If you know double quote is before the Id then take index of id - 1?
string myString = #"String with ""id:"" in it";
var indexOfId = myString.IndexOf("id:") - 1;
Console.WriteLine(#"Index of ""id:"" is {0}", indexOfId);
Reading between the lines, if this is a JSON string, and you have .NET 4 or higher available, you can ask .NET to deserialize the string for you rather than parsing by hand: see this answer.
Alternatively you might consider Json.NET if you're working very heavily with JSON.
Otherwise, as others note, you need to escape the quotes, so for example:
text.IndexOf("\"id:\"")
text.IndexOf(#"""id:""")
or for overengineered legiblity:
string Quoted(string text)
{
return "\"" + text + "\""; // generates unnecessary garbage
}
text.IndexOf(Quoted("id:"))

Fetching a segment of the URL in the address bar

This is what I tried:
string myURL= "http://mysite.com/articles/healthrelated";
String idStr = myURL.Substring(myURL.LastIndexOf('/') + 1);
I need to fetch "healthrelated" ie the text after the last slash in the URL. Now the problem is that my URL can also be like :
"http://mysite.com/articles/healthrelated/"
ie "a Slash" at the end of that text too. Now the last slash becomes the one AFTER "healthrelated" and so the result I get using
String idStr = myURL.Substring(myURL.LastIndexOf('/') + 1);
is empty string..
what should my code be like so I always get that text "healthrelated" no matter if there's a slash in the end or not. I just need to fetch that text somehow.
Try this.
var lastSegment = url
.Split(new string[]{"/"}, StringSplitOptions.RemoveEmptyEntries)
.ToList()
.Last();
Why don't you use Uri class of .NET and use segments property:
http://msdn.microsoft.com/en-us/library/system.uri.segments.aspx
What you can do in this situation is either using REGEX (which I'm not an expert on, but I'm shure other ppl here are ;) ) or a simple:
string[] urlParts = myURL.Split('/');
and take the last string in this array.

string[] management

ok, so ill cut to the chase here. and to be clear, im looking for code examples where possible.
so, i have a normal string, lets say,
string mystring = "this is my string i want to use";
ok, now that i have my string, i split it by the space with
string[] splitArray = mystring.Split(new char[] { ' ' });
ok, so now i have splitArray[0] through splitArray[7].
now, i need to do some fancy things with the string that i normally wouldnt need to do.
here are a few:
i need to cut off the first word, so i am left with the other 7 words, so that i have something like:
string myfirstword = "this";
mystring = "is my string i want to use";
now, i will need to use mystring over and over again, using different parts of it at different times, and depending on the string i will have no idea how long, it will be. so i will give some examples of things ill need.
first, ill need to know, how many words are there (this is easy, just throwing it in)
second, ill need some way of using things like,
string secondword = splitArray[1];
string everythingAfterTheSecondWord = splitArray[2+];
if you noticed, i included a [2+] ... the + indicating that i want all strings in the array put back together, spaces in all, into a string. so for example,
string examplestring = "this is my example for my stack overflow question";
string[] splitArray2 = examplestring.Split(new char[] { ' ' });
now, if i called on splitArray2[4+] i would want a return of "for my stack overflow question". now obviously its not as simple as adding a + to a string array.. but thats what i need, and under the current situation i have tried many other easier ways that simply to not work.
ALSO, if i called on something like splitArray2[2-5] i would want, words 2 through 5 obviously.
Summary:
i need greater management of my string[] arrays, and i need to be able to find, every word after word *, need to be able to strip out random words in the string while leaving the rest of the string intact, and need to be able to find string m through n
Thanks!
Most of what you're looking for can be achieved with a List<string>. Briefly:
string mystring = "this is my string i want to use";
List<string> splitArray = new List<string>(mystring.Split(new char[] { ' ' }));
string firstWord = splitArray[0];
// mystring2 = "is my string i want to use"
splitArray.RemoveAt(0);
string mystring2 = String.Join(" ", splitArray.ToArray());
To do the more complicated things you describe with splitArray[2+] requires LINQ though, and hence .NET 3.5.
List<string> everythingAfterTheSecondWord = splitArray.Skip(2).ToList();
For splitArray[2-5]:
List<string> arraySlice = splitArray.Skip(2).Take(3).ToList();
Well, to do the "every word starting at word X" you could do this:
string newString = string.join(splitArray," ",x);
To get y words starting at x, do this:
string newString = string.join(splitArray," ",x,y);
To get the number of words:
int wordCount= splitArray.Length;
Putting it all together, words x-y goes like this:
string newString = string.join(splitArray," ",x, splitArray.Length-x+1);

Categories

Resources