How to append double quote character to a string? - c#

I'm trying to create a C# property as a string as part of an experiment, but I'm getting the error "Input string was not in the correct format".
Is this because of the quote?
How can I properly append the double quote character to the string?
this is the code:
string quote = "\"";
string propName = "MyPropName";
string propVal = "MyPropVal";
string csProperty = string.Format("public string {0} { get { return {1}; } }", propName, quote + propVal + quote);

Escape the braces (by doubling) that are not part of the format mask:
string csProperty = string.Format("public string {0} {{ get {{ return {1}; }} }}", propName, quote + propVal + quote);

Related

Split null or space on the first of a string?

I'm getting a string " abc df fd";
I want to split a space or null of string. As result is "abc df fd" That such I want;
private string _senselist;
public string senselist
{
get
{
return _senselist;
}
set
{
_senselist = value.Replace("\t", "").Replace(" "," ").Split(,1);
}
}
To remove spaces from the begining and the ending of a string, you can use Trim() method.
string data = " abc df fd";
string trimed = data.Trim(); // "abc df fd"
On your code add Trim at the end, instead of Split
_senselist = value.Replace("\t", "").Replace(" "," ").Trim();
As #andrei-rînea recommended you can also check TrimStart(' ') and TrimEnd(' ').

Escaping reverse backSlash

I want to display data in this format yyyy/mm/dd
How I can do it? When I use
String.Format("{0:yyyy/MM/dd}", Model.RequiredDate)
I get yyyy.mm.dd
You can escape it like;
String.Format("{0:yyyy'/'MM'/'dd}", Model.RequiredDate)
I strongly suspect your CurrentCulture's DateSeparator is ., that's why / format specifier replace itself to it.
What about this option?
string DateToString(DateTime date, string seperator)
{
return date.ToString("yyyy") + seperator + date.ToString("MM") + seperator + date.ToString("dd");
}
But as Soner Gönül said, you can also escape it like this:
String.Format("{0:yyyy'/'MM'/'dd}", Model.RequiredDate)
EDIT:
What about this two options?
string DateToString(DateTime date, string seperator, string first, string second, string third)
{
return date.ToString(first) + seperator + date.ToString(second) + seperator + date.ToString(third);
}
string DateToString(DateTime date, string seperator, string[] format)
{
string result = "";
foreach (string s in format)
{
s += (date.ToString(s) + seperator);
}
return result;
}

The best way to split a string without a separator

I have string:
MONEY-ID123456:MONEY-STAT43:MONEY-PAYetr-1232832938
From the string above you can see that it is separated by colon (:), but in the actual environment, it does not have a standard layout.
The standard is the fields name, example MONEY-ID, and MONEY-STAT.
How I can I split it the right way? And get the value from after the fields name?
Something like that should work:
string s = "MONEY-ID123456:MONEY-STAT43:MONEY-PAYetr-1232832938";
Regex regex = new Regex(#"MONEY-ID(?<moneyId>.*?)\:MONEY-STAT(?<moneyStat>.*?)\:MONEY-PAYetr-(?<moneyPaetr>.*?)$"); Match match = regex.Match(s);
if (match.Success)
{
Console.WriteLine("Money ID: " + match.Groups["moneyId"].Value);
Console.WriteLine("Money Stat: " + match.Groups["moneyStat"].Value);
Console.WriteLine("Money Paetr: " + match.Groups["moneyPaetr"].Value);
}
Console.WriteLine("hit <enter>");
Console.ReadLine();
UPDATE
Answering additional question, if we're not sure in format, then something like the following could be used:
string s = "MONEY-ID123456:MONEY-STAT43:MONEY-PAYetr-1232832938";
var itemsToExtract = new List<string> { "MONEY-STAT", "MONEY-PAYetr-", "MONEY-ID", };
string regexFormat = #"{0}(?<{1}>[\d]*?)[^\w]";//sample - MONEY-ID(?<moneyId>.*?)\:
foreach (var item in itemsToExtract)
{
string input = s + ":";// quick barbarian fix of lack of my knowledge of regex. Sorry
var match = Regex.Match(input, string.Format(regexFormat, item, "match"));
if (match.Success)
{
Console.WriteLine("Value of {0} is:{1}", item, match.Groups["match"]);
}
}
Console.WriteLine("hit <enter>");
Console.ReadLine();
As Andre said, I would personally go with regular expressions.
Use groups of something like,
"MONEY-ID(?<moneyid>.*)MONEY-STAT(?<moneystat>.*)MONEY-PAYetr(?<moneypay>.*)"
See this post for how to extract the groups.
Probably followed by a private method that trims off illegal characters in the matched group (e.g. : or -).
Check this out:
string regex = #"^(?i:money-id)(?<moneyid>.*)(?i:money-stat)(?<moneystat>.*)(?i:money-pay)(?<moneypay>.*)$";
string input = "MONEY-ID123456:MONEY-STAT43:MONEY-PAYetr-1232832938";
Match regexMatch = Regex.Match(input, regex);
string moneyID = regexMatch.Groups["moneyid"].Captures[0].Value.Trim();
string moneyStat = regexMatch.Groups["moneystat"].Captures[0].Value.Trim();
string moneyPay = regexMatch.Groups["moneypay"].Captures[0].Value.Trim();
Try
string data = "MONEY-ID123456:MONEY-STAT43:MONEY-PAYetr-1232832938";
data = data.Replace("MONEY-", ";");
string[] myArray = data.Split(';');
foreach (string s in myArray)
{
if (!string.IsNullOrEmpty(s))
{
if (s.StartsWith("ID"))
{
}
else if (s.StartsWith("STAT"))
{
}
else if (s.StartsWith("PAYetr"))
{
}
}
}
results in
ID123456:
STAT43:
PAYetr-1232832938
For example, using regular expressions,
(?<=MONEY-ID)(\d)*
It will extract
123456
from your string.

c# Searching for a string that contains quotes

I am fairly new to c# and am working on a little project but got stuck on this. I have a file that contains some assembly code. I want my program to search this file for a string, actually a value right after my string. One of the strings i am searching for is:
setproperty QName(PackageNamespace(""), "font")
getlocal 4
pushint
My search code is this:
private void searchFile(String searchText)
{
System.IO.StreamReader reader = new System.IO.StreamReader(file);
String text = reader.ReadToEnd();
if (Regex.IsMatch(text, searchText))
{
MessageBox.Show(searchText + " was found in the given file", "Finally!!");
}
else
{
MessageBox.Show("Sorry, but " + searchText + " could not be found in the given file", "No Results");
}
}
//when i click a button//
searchFile(#"setproperty QName(PackageNamespace(""""), ""font"")
getlocal 4
pushint ");
I know that the string is in the file but the result comes up with not found. I don't know if it is the quotes or tabs or both that is causing this.
Here is part of the file:
getlocal 4
pushstring "Verdana"
setproperty QName(PackageNamespace(""), "font")
getlocal 4
pushint 16764170
setproperty QName(PackageNamespace(""), "color")
getlocal 4
pushbyte 12
setproperty QName(PackageNamespace(""), "size")
My second question is how can i get the value of the first int after my search result?
Thanks in advance.
-Leen
You should change your method like this:
private static string searchFile(String searchText)
{
System.IO.StreamReader reader = new System.IO.StreamReader("test.txt");
String text = reader.ReadToEnd();
int poz = text.IndexOf(searchText);
if (poz >= 0)
{
int start = poz + searchText.Length;
int end = text.IndexOf("\n", start);
Console.WriteLine(searchText + " was found in the given file", "Finally!!");
return text.Substring(start, end - start);
}
else
{
Console.WriteLine("Sorry, but " + searchText + " could not be found in the given file", "No Results");
return string.Empty;
}
}
The call:
string val = searchFile("setproperty QName(PackageNamespace(\"\"), \"font\")\r\n\r\n getlocal 4\r\n pushint ");
So I think you may be use to VB.net. C-based languages (like c#) used the backslash character "\" as an escape character.
So in a searching for a double-quote in a string you would need to escape it using \".
I believe what you're looking for is:
searchFile(#"setproperty QName(PackageNamespace(\"\"), \"font\")
getlocal 4
pushint ");
But this isn't really a regular expression, which is what the Regex class is meant for. So I would (well not really, I would clean it up a bit, like not mix my UI and bizlogic) do this:
// Added String as the function type so you can return the matched "Integer" as a string, you could always do a Int32.TryParse(...)
private String searchFile(String file, String searchText)
{
System.IO.StreamReader reader = new System.IO.StreamReader(file);
String text = reader.ReadToEnd();
int32 index = text.IndexOf(searchText);
if (index >= 0) //We could find it at the very beginning
{
MessageBox.Show(searchText + " was found in the given file", "Finally!!");
int32 start = index + searchText.Length;
int32 end = Regex.Match(text, "[\n\r\t]", index).Index; // This will search for whitespace
String value = text.Substring(start, end - start);
// Now you can do something with your value, like...
return value;
}
else
{
MessageBox.Show("Sorry, but " + searchText + " could not be found in the given file", "No Results");
return "";
}
}

Replace double quotes in json string with empty string

I have problem with deserialization of json string, because string is bad format.
For example json object consist string property statusMessage with value "Hello "dog" ".
The correct format should be "Hello \" dog \" " .
I would like remove double quotes from this property.
Something Like this. "Hello "dog" ". -> "Hello dog ".
Here is it original json string which I work.
"{\"jancl\":{\"idUser\":18438201,\"nick\":\"JANCl\",\"photo\":\"1\",\"sex\":1,\"photoAlbums\":1,\"videoAlbums\":0,\"sefNick\":\"jancl\",\"profilPercent\":75,\"emphasis\":false,\"age\":\"-\",\"isBlocked\":false,\"PHOTO\":{\"normal\":\"http://u.aimg.sk/fotky/1843/82/n_18438201.jpg?v=1\",\"medium\":\"http://u.aimg.sk/fotky/1843/82/m_18438201.jpg?v=1\",\"24x24\":\"http://u.aimg.sk/fotky/1843/82/s_18438201.jpg?v=1\"},\"PLUS\":{\"active\":false,\"activeTo\":\"0000-00-00\"},\"LOCATION\":{\"idRegion\":\"6\",\"regionName\":\"Trenčiansky kraj\",\"idCity\":\"138\",\"cityName\":\"Trenčianske Teplice\"},\"STATUS\":{\"isLoged\":true,\"isChating\":false,\"idChat\":0,\"roomName\":\"\",\"lastLogin\":1294925369},\"PROJECT_STATUS\":{\"photoAlbums\":1,\"photoAlbumsFavs\":0,\"videoAlbums\":0,\"videoAlbumsFavs\":0,\"videoAlbumsExts\":0,\"blogPosts\":0,\"emailNew\":0,\"postaNew\":0,\"clubInvitations\":0,\"dashboardItems\":1},\"STATUS_MESSAGE\":{\"statusMessage\":\"\"Status\"\",\"addTime\":\"1294872330\"},\"isFriend\":false,\"isIamFriend\":false}}"
Problem is here, json string consist this object:
"STATUS_MESSAGE": {"statusMessage":" "some "bad" value" ", "addTime" :"1294872330"}
Condition of string which I want modified:
string start with "statusMessage":"
string can has any *lenght from 0 -N *
string end with ", "addTime
So I try write pattern for string which start with "statusMessage":", has any lenght and is ended with ", "addTime.
Here is it:
const string pattern = " \" statusMessage \" : \" .*? \",\"addTime\" ";
var regex = new Regex(pattern, RegexOptions.IgnoreCase);
//here i would replace " with empty string
string result = regex.Replace(jsonString, match => ???);
But I think pattern is wrong, also I don’t know how replace double quotes with empty string (remove double quotes).
My goal is :
"statusMessage":" "some "bad" value"
to "statusMessage":" "some bad value"
Thank for advice
To serialize json on client side I use something like this:
var JSON = JSON || {};
JSON.stringify = JSON.stringify || function (obj) {
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"' + obj + '"';
return String(obj);
}
else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n]; t = typeof (v);
if (t == "string") v = '"' + v + '"';
else if (t == "object" && v !== null) v = JSON.stringify(v);
json.push((arr ? "" : '"' + n + '":') + String(v));
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
};
then
$.ajax({
...
data: JSON.stringify({
someThing1: [
{ Id: '001', FooValue: ''},
{ Id: '002', FooValue: ''}
],
someThing2: [
{ Id: '001', FooValue: ''},
{ Id: '002', FooValue: ''}
]
}),
...
});
On server-side I use Newton.Json ( http://james.newtonking.com/pages/json-net.aspx )
object deserializeObject = JsonConvert.DeserializeObject(requestParameterTextRepresentation, RootType);
If you have no ability to modify client-side script to pass correct json-string, then all your regexps are vain effort.
This should do it:
var str = '"STATUS_MESSAGE": {"statusMessage":" "some "bad" value" ", "addTime" :"1294872330"}"';
str = str.replace(/("statusMessage"\s*:\s*")(.+?)("\s*,\s*"addTime)/, function(m0,m1,m2,m3) { return m1 + m2.replace(/"/g,'') + m3; });
//now str == "STATUS_MESSAGE": {"statusMessage":" some bad value ", "addTime" :"1294872330"}"
Edit: sorry i don't know why i confused this with a javascript question :s - You are able to do a very similar approach in c# tho i can't come up with the syntax right now.
While it is an extremely weak, hacky, solution, this should work in simple cases:
string pattern = #"(?<=""statusMessage"":"").*?(?="",""addTime"")";
string result = Regex.Replace(malformedJSON, pattern,
match => match.Value.Replace("\"", ""));
I'm using lookarounds to find the string, and then remove all quotes from it. You may also escape them by replacing with "\\\"".
Try This (Not a perfect solution though):
string data = "\"STATUS_MESSAGE\": {\"statusMessage\":\" \"some \"bad\" value\" \", \"addTime\" :\"1294872330\"}";
Regex rxStatusMessage = new Regex("\\s*\"statusMessage\"\\s*:\"\\s*");
Regex rxAddTime = new Regex("\",\\s*\"addTime\"\\s*:");
data = rxStatusMessage.Replace(data, "\x02");
data = rxAddTime.Replace(data, "\x03");
Regex rxReplace = new Regex("\x02.*\x03");
data = rxReplace.Replace(data, m => m.Value.Replace("\"", ""));
data = data.Replace("\x02", "\"statusMessage\":\"");
data = data.Replace("\x03", "\", \"addTime\" :");

Categories