This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can I convert a C# string value to an escaped string literal
How can i entitize an arbitrary string to get exact human readable view similar to what the debugger does? I.e. i want all special characters entitized:
"Hello,\r\nworld"
"Hello,#D$#A$world"
"Hello,0x0D0x0Aworld"
any output like that will be fine. I'm only interested in standard function in BCL (maybe some escape routine in existing serializers or helper classes, whatever). Reverse function would be cool as well.
I do not think that there is out of the box solution for your needs.
Char.Isxxx can be used to find characters that needs special processing and custom code can replace them with info you want to see.
Code below works fine for sample but there is to many different characters in Unicode to be sure that it covers all the cases.
var s = #"Hello,
world";
var builder = new StringBuilder();
foreach (var c in s)
{
if (Char.IsLetterOrDigit(c) || Char.IsPunctuation(c))
builder.Append(c);
else
{
var newStr = string.Format("#{0}$", ((int)c).ToString("X"));
builder.Append(newStr);
}
}
Console.WriteLine(builder.ToString());
Result shown in console:
Hello,#D$#A$world
You can use a series of String.Replaces:
string Entitize(string input)
{
return input.Replace("\n", "\\n").Replace("\r", "\\r"), ... ;
}
Related
This question already has an answer here:
Learning Regular Expressions [closed]
(1 answer)
Closed 6 years ago.
How can I simply check if a string contains {x} (x can be any number)?
I guess there is some simple RegEx to do this.
"This string contains {0} a placeholder".HasPlaceholder == true
and
"This string contains no placeholder".HasPlaceholder == false
You can write a simple extension and use a regex:
public static class StringExtensions
{
public static bool HasPlaceholder(this string s)
{
return Regex.IsMatch(s, "{\\d+}");
}
}
This regex works only for the placeholders you specified (containing only a number).
For a full placeholder you would need something like "{\\d+(,-?\\d+)?(:[A-Z]\\d*)?}". But this still needs refinement. See "Standard Numeric Format Strings" for a full list of valid symbols.
You can use this extension like this:
string s = "This string contains {0} a placeholder";
if (s.HasPlaceholder())
Console.WriteLine("Contains placeholders");
This question already has answers here:
Make first letter of a string upper case (with maximum performance)
(42 answers)
Closed 7 years ago.
I have already taken a look at such posts like:
Format to first letter uppercase
How to capitalise the first letter of every word in a string
But none of these seem to actually work. I would have thought to start with that there would just be a:
.Capitalize();
Like there is:
.Lower(); & .Upper();
Are there any documentation or references regarding converting to a string like the following?
string before = "INVOICE";
To then becoming:
string after = "Invoice";
I receive no errors using the way the posts solutions I read give me, however, the before still remains capitalized.
What about using ToUpper on the first char and ToLower on the remaining string?
string after = char.ToUpper(before.First()) + before.Substring(1).ToLower();
You can create a method that does something like this:
string UppercaseFirst(string str)
{
if (string.IsNullOrEmpty(str))
return string.Empty;
return char.ToUpper(str[0]) + str.Substring(1).ToLower();
}
And use it like this:
string str = "thISstringLOokSHorribLE";
string upstr = UppercaseFirst(str);
to get this:
Thisstringlookshorrible
I have a text file that contain only the FULL version number of an application that I need to extract and then parse it into separate Variables.
For example lets say the version.cs contains 19.1.354.6
Code I'm using does not seem to be working:
char[] delimiter = { '.' };
string currentVersion = System.IO.File.ReadAllText(#"C:\Applicaion\version.cs");
string[] partsVersion;
partsVersion = currentVersion.Split(delimiter);
string majorVersion = partsVersion[0];
string minorVersion = partsVersion[1];
string buildVersion = partsVersion[2];
string revisVersion = partsVersion[3];
Altough your problem is with the file, most likely it contains other text than a version, why dont you use Version class which is absolutely for this kind of tasks.
var version = new Version("19.1.354.6");
var major = version.Major; // etc..
What you have works fine with the correct input, so I would suggest making sure there is nothing else in the file you're reading.
In the future, please provide error information, since we can't usually tell exactly what you expect to happen, only what we know should happen.
In light of that, I would also suggest looking into using Regex for parsing in the future. In my opinion, it provides a much more flexible solution for your needs. Here's an example of regex to use:
var regex = new Regex(#"([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9])");
var match = regex.Match("19.1.354.6");
if (match.Success)
{
Console.WriteLine("Match[1]: "+match.Groups[1].Value);
Console.WriteLine("Match[2]: "+match.Groups[2].Value);
Console.WriteLine("Match[3]: "+match.Groups[3].Value);
Console.WriteLine("Match[4]: "+match.Groups[4].Value);
}
else
{
Console.WriteLine("No match found");
}
which outputs the following:
// Match[1]: 19
// Match[2]: 1
// Match[3]: 354
// Match[4]: 6
This question already has answers here:
Split String in C#
(9 answers)
Closed 7 years ago.
I've a string like this
cscript "E:\Data\System Test Performance\Some Tool\script.vbs" "AP_TEST" %%PARM1
I'm splitting above string like below
cmd.Split(' ')
Expected:
cscript
"E:\Data\System Test Performance\Some Tool\script.vbs"
"AP_TEST"
%%PARM1
But Actual results
There is a space in the string so your result is as expected. Try splitting on the quote instead:
var str = #"cscript ""E:\Data\System Test Performance\Some Tool\script.vbs"" ""AP_TEST"" %%PARM1";
str.Split('"').Select (s => s.Trim()).Where (s => !string.IsNullOrEmpty(s));
You need to write your own split function which supports text qualifiers
Check answer here Split String in C#
Or this article http://www.codeproject.com/Articles/15361/Split-Function-that-Supports-Text-Qualifiers
This might do the trick for you
string[] newinp = Regex.Split(inp, "(?=\")").Where(x => !string.IsNullOrEmpty(x)).ToArray();
There are so many spaces in your E:\Data\System Test Performance\Some Tool\script.vbs (file location) thats why you're getting the wrong array.
You may do two things
1) Make directory which doesn't contains spaces
2) Modify code
string[] final=new string[4];
final[0]=cmdLinesplit[0];
final[2]=cmdLinesplit[cmdLinesplit.Length-2];
final[3]=cmdLinesplit[cmdLinesplit.Length-1];
for(int i=1;i< cmdLinesplit.Length-2;i++)
{
final[1] +=cmdLinesplit[i]+" ";
}
final[1].Trim();
This question already has answers here:
Escape a string in SQL Server so that it is safe to use in LIKE expression
(6 answers)
Closed 5 years ago.
UPDATE
Following four characters need to be escaped when '\' is the escape helper %[]_
http://msdn.microsoft.com/en-us/library/aa933232(v=sql.80).aspx - LIKE
Escape a string in SQL Server so that it is safe to use in LIKE expression
How do I escape _ in SQL Server?
QUESTION
Though I searched a lot, I could not find out a problem exactly matching the following, in stack overflow.
I have a database column called Log_Description. It has two records.
1) "Sample % value record"
2) "Sample free record"
I am using SQL Command and setting parameters as shown below
commandText = commandText + “Log_Description LIKE #Log_Description”;
command.Parameters.AddwithValue(“#Log_Description”, “%”+obj. LogDescription+”%”);
Suppose the user enters “%” as search param for txtLogDescription textbox, I need to show only first record. But currently it is showing both the records.
What are the possible ways to overcome this?
What are the other characters that may cause such issues with the above code?
Note: I cannot prevent user from entering “%” as input
Note: I am using SQL Server as database
EDIT:
Solution I am using now is Escaping the escape character does not work – SQL LIKE Operator
private static string CustomFormat(string input)
{
input = input.Replace(#"\", #"\\");
input = input.Replace(#"%", #"\%");
input = input.Replace(#"[", #"\[");
input = input.Replace(#"]", #"\]");
input = input.Replace(#"_", #"\_");
return input;
}
LINQ approach (with performance hit) is below
Collection<Log> resultLogs = null;
if (!String.IsNullOrEmpty(logSearch.LogDescription))
{
resultLogs = new Collection<Log>();
var results = from o in logs where o.LogDescription.Contains(logSearch.LogDescription) select o;
if (results != null)
{
foreach (var log in results)
{
resultLogs.Add((Log) log);
}
}
}
else
{
resultLogs = logs;
}
As far as escaping %, see Tommy Grovnes' comment on the question.
If you can use a List<T> instead of a Collection<T> (see here), this can be written more concisely:
var descr = logSearch.logDescription;
var results = (
from o in logs
where String.IsNullOrEmpty(descr) ||
o.LogDescription.Contains(descr)
select o
).ToList();
If you still need a Collection<T>, you can wrap the results of the LINQ query in a Collection constructor:
var results = new Collection<Log>((
from o in logs
where String.IsNullOrEmpty(descr) ||
o.LogDescription.Contains(descr)
select o
).ToList());