This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Can I convert a C# string value to an escaped string literal
How I can show the contents of a string in 'pure mode',including \r,\n,\t etc..
equivalent to .toSource() method of javascript
For example:
JavaScript:
var str = "foo\nbaa\ttest";
console.log(str.toSource());
Output:
(new String("foo\nbaa\ttest"))
it is possible do this in C#?
Thanks in advance!
See the answer to Can I convert a C# string value to an escaped string literal . He wrote this extension method that does exactly what you're wanting:
static string ToLiteral(string input)
{
var writer = new StringWriter();
CSharpCodeProvider provider = new CSharpCodeProvider();
provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
return writer.GetStringBuilder().ToString();
}
Regex.Escape("foo\nbaa\ttest")
Looking at the general problem - reconstructing some source code - there is no language option on C# that would let you do it automagically.
However (this is theory on my part) you should be able to use expressions to get to the IL equivalent (using the Reflection.Emit or Mono.Cecil libraries perhaps). You could I suspect then use the libraries from the ILSpy project to reconstruct the C#.
Related
This question already has answers here:
Regex escape with \ or \\?
(5 answers)
Convert C# string to JavaScript String
(3 answers)
Closed 4 years ago.
Salaam
I am looking for a proper version of a C# or Razor equivalent of PHP's addSlashes. That would add
\ to some\string => some\\string
Please provide help
Why I needed this
In my application a user entered Sometext in textbox was accidently pressed next time when page when data was populated though Razor it was like this
...append('<span>'+'#Model.value'+'</span>')
=> after compiling it becomes like this
...append('<span>'+'sometext\'+'</span>')
so with this scenario my javascript code broke at '\' because now single quote has started but not ending due to ``. So i thought instead of limiting characters i would rather add slashes through C# code
Thank You
You don't show any code you've already written, but this can be done by using [string.replace()] ( https://www.w3schools.com/jsref/jsref_replace.asp ) :
var str = "This is \\a test";
var replaced = str.replace("\\", "\\\\");
Whoops - you want the answer in C# , I misread your "javascript" tag. It's mostly the same:
string str = "This is \\a test";
string replaced = str.Replace("\\", "\\\\");
Also see C# String Replace
After the update, https://stackoverflow.com/a/27574931/34092 is most likely a much better answer.
This question already has answers here:
C# string replace does not actually replace the value in the string [duplicate]
(3 answers)
Closed 5 years ago.
I have this String
link="https%3a%2f%2fen.wikipedia.org%2fwiki%2fHuawei/"
which shoud be like this:
link="https://en.wikipedia.org/wiki/Huawei/"
I wrote this code:
link.Replace("%2f", "/");
link.Replace("%3a", ":");
But it did not work.
Instead of trying to decode the URL yourself I'd use HttpUtility.UrlDecode
HttpUtility.UrlDecode("https%3a%2f%2fen.wikipedia.org%2fwiki%2fHuawei/")
"https://en.wikipedia.org/wiki/Huawei/"
See: https://msdn.microsoft.com/en-us/library/system.web.httputility.urldecode(v=vs.110).aspx
String.Replace does return the value replaced try:
link = link.Replace("%2f", "/");
link is a string and is not mutating when you call the Replace method
link.Replace will not affect the link object itself, instead it returns a new String
from the doc emphasis mine:
Returns a new string in which all occurrences of a specified Unicode
character in this instance are replaced with another specified Unicode
character.
do instead:
link = link.Replace("%2f", "/"); or
link = link.Replace("%3a", ":");
This question already has answers here:
How can I strip HTML tags from a string in ASP.NET?
(14 answers)
Closed 7 years ago.
I have a string defined like so:
private const String REFER_TO_BUSINESS = "<pre> (Refer to business office for guidance and explain below the circumstances for exception to policy or attach a copy of request)</pre>";
...which has, as you can see, the "pre" tag to preserve the space prepended to the verbiage. I want to, though, reference this string without the "pre" tags. It would be easy enough to search for "<pre>" and "</pre>" and remove them, but it would quickly become tedious to do that with every HTML tag type.
How can I, in C#, strip all tags out of a string, regardless of whether they are "<pre>", "<h1>", "<span>", "<aside>" or anything else?
Try a regex replacement.
This pattern matches html tags within a string. From here
var pattern = #"</?\w+((\s+\w+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>";
var source = "<pre> (Refer to business office for guidance and explain below the circumstances for exception to policy or attach a copy of request)</pre>";
Regex.Replace(source, pattern, string.Empty);
This should do what you need it to do:
string stripMeOfHTML = Regex.Replace(stripMeOfHTML, #"<[^>]+>", "").Trim();
This works:
// For strings that have embedded HTML tags for presentation on the form (such as "<pre>" and such), but need to be rendered free of these (such as on the PDF)
private String RemoveHTMLTags(String stringContainingHTMLTags)
{
String regexified = Regex.Replace(stringContainingHTMLTags, "<.*?>", string.Empty);
return regexified;
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to parse a query string into a NameValueCollection in .NET
I have input as
https://localhost:8181/PortalSite/View/CommissionStatement.aspx?status=commission&quarter=1;
Output needed
status=commission
How to do in C#(preferably regular expression or something else)..
My solution
var res = src.Split('?')[1].Split('=')[1].Split["&"][0];
but failing in Split["&"]
If what you're going for is guaranteed to be a URL with a query string, I would recommend the HttpUtility.ParseQueryStringMethod.
var result = HttpUtility.ParseQueryString(new Uri(src).Query);
Note that in cases like this, the common fallacy is to just put together some string handling function that cannot deal with the full possible spec of input. In your case, there are a lot of valid URLs that are actually rather hard to handle/parse correctly. So you should stick to the already implemented, proven classes.
Thus, I would use the System.Uri class to consume the URL string. The part of the URL you're actually trying to access is the so called "query", which is also a property of the Uri instance. The query itself can easily and correctly be accessed as its individual key-value parts using the System.Web.HttpUtility.ParseQueryStringMethod() (you need to add System.Web.dll to your project's references and make sure you're not using the .NET 4 client profile for your application, as that will not include this assembly).
Example:
Uri u = new Uri("https://localhost:8181/PortalSite/View/CommissionStatement.aspx?status=commission&quarter=1;");
Console.WriteLine(u.Query); // Prints "status=commission&quarter=1;"
var parameters = HttpUtility.ParseQueryString(u.Query);
Console.WriteLine(parameters["status"]); // Prints "commission"
Once you have the "parameters" you could also iterate over them, search them, etc. YMMV.
If you require the output you show in your question, thus know that you always need the first parameter of the query string (and are not able to look it up by name as I show above), then you could use the following:
string key = parameters.GetKey(0);
Console.WriteLine(key + "=" + parameters[key]); // Prints "status=commission"
You could use the following regex: status=(\w*)
But I think there are better alternatives like using HttpUtility.ParseQueryStringMethod.
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
In C# what is the difference between String and string
String vs string in C#
Hi,
Can anyone tell me the difference between the two lines of code below:
public const String sample = "Sample";
public const string sample2 = "Sample2";
Both "String" and "string" are of System.String.
Thanks in advance.
These data types are exactly the same, as string is just an alias for the class String. If you have a look, there are similar capitalized and non capitalized versions of int, float and similar classes.
Have a look here for a more detailed answer.
There are the same
string is an alias in the C# for .Net System.String, like int is for Int32, long is for int64 and etc. C# string replaced by System.String during compilation
No difference what so ever - in fact you can write the following code:
String sample = "Sample";
string sample2 = sample;
Both maps to the same IL string type
String vs string in C#
String stands for System.String and it is a .NET Framework type. string is an alias in the C# language for System.String. Both of them are compiled to System.String in IL (Intermediate Language), so there is no difference. Choose what you like and use that. If you code in C#, I'd prefer string as it's a C# type alias and well-know by C# programmers.
String is CTS type but string is c# string object.
You can use String to any of dot net language.
both are the same
string -> c# type which gets converted to
String -> .net type
String is the .NET class for the CLR built-in string type. string is the C# language identifier that maps to the CLR String type. They are the same thing.
"string" is actually an alias for System.String. They're the same.
Try:
typeof(string) == typeof(String) == typeof(System.String)
Nothing really, in C# the type keywords actually are synonyms for the types. So int = System.Int32 short = System.Int16 and string = System.String.
They have the keywords because they are easier to remember and programmers coming from other languages like c/c++ would also be familiar with these types.
Anyway, look at the C# keyword reference and you can find these things out. This was taken from the string keyword reference.
The string type represents a string of Unicode characters. string is an alias for String in the .NET Framework. Strings are immutable--the contents of a string object cannot be changed after the object is created.