On the client, I have a textarea and I extract its value like this:
var TheURIEncodedString = encodeURI($('#TheTextArea').val());
The string then looks like this:
"This%20is%20a%20test%0AThis%20is%20a%20new%20line"
I send this string via ajax and when I receive it on the server, I need to count the number of actual characters, not the length of the string.
How can I do this?
Use HtppUtility.UrlDecode:
HttpUtility.UrlDecode("This%20is%20a%20test%0AThis%20is%20a%20new%20line").Length;
Result:
This is a test
This is a new line
Use the HtppUtility.UrlDecode method
int numberOfCharacters =
HttpUtility.UrlDecode("This%20is%20a%20test%0AThis%20is%20a%20new%20line").Length;
Related
I am going to convert byte array into string using below method.
string data = Encoding.Default.GetString(e.Data);
But this string has the following special characters which I needed to avoid from the string itself.
As you can see in the data I am getting space before the '7h' and some '\rL' getting added after the text. I used trim() function. But it didn't work for the following case.
Please advice.
If you know exactly symbols you whant remove, just replace it:
var data = "⏩Some⏬String";
var clearedData = data.Replace("⏩", string.Empty).Replace("⏬", string.Empty);
result:
SomeString
I get error "Input string was not in correct format" when parsing to int.
But string is in correct format. I'm adding screenshot below.
The problem is that there must be some hidden characters in your a string variable (Carriage Return maybe?). Try int.Parse(a.Substring 0,4) as usually they are at the end of the string.
You could also clean the input where you are getting that value from.
I noticed you are doing multiple conversions. Are you sure it's a ("2016") that is causing the error?
if yes, then there must be hidden characters as other have suggested. The a.substring(0,4) would indeed remove any trailing characters. But if the first character is a hidden char, it would not.
string output = new string(input.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray());
should clear out any possible hidden characters.
Maybe you can try something like this:
int x = Convert.ToInt32(a);
Furthermore you can try to use the .ToString() Methode of a to make it run more stable.
You can additionaly try to clear the string from all "non number" chars using Rexex:
/// <summary>
/// RegEx to extract all non numeric values.
/// </summary>
private static readonly Regex rxNonDigits = new Regex(#"[^\d.,-]+");
Use it as follows to clear:
String a2 = rxNonDigits.Replace(a, "");
I think you are using REST API with JSON or passing whole string in query string i.e JSON formatted string, then you should use
a = new JavaScriptSerializer().Deserialize(a, null).ToString();
x = int.Parse(a);
So I have this file with a number that I want to use.
This line is as follows:
TimeAcquired=1433293042
I only want to use the number part, but not the part that explains what it is.
So the output is:
1433293042
I just need the numbers.
Is there any way to do this?
Follow these steps:
read the complete line
split the line at the = character using string.Split()
extract second field of the string array
convert string to integer using int.Parse() or int.TryParse()
There is a very simple way to do this and that is to call Split() on the string and take the last part. Like so if you want to keep it as a string:
var myValue = theLineString.Split('=').Last();
If you need this as an integer:
int myValue = 0;
var numberPart = theLineString.Split('=').Last();
int.TryParse(numberPart, out myValue);
string setting=sr.ReadLine();
int start = setting.IndexOf('=');
setting = setting.Substring(start + 1, setting.Length - start);
A good approach to Extract Numbers Only anywhere they are found would be to:
var MyNumbers = "TimeAcquired=1433293042".Where(x=> char.IsDigit(x)).ToArray();
var NumberString = new String(MyNumbers);
This is good when the FORMAT of the string is not known. For instance you do not know how numbers have been separated from the letters.
you can do it using split() function as given below
string theLineString="your string";
string[] collection=theLineString.Split('=');
so your string gets divided in two parts,
i.e.
1) the part before "="
2) the part after "=".
so thus you can access the part by their index.
if you want to access numeric one then simply do this
string answer=collection[1];
try
string t = "TimeAcquired=1433293042";
t= t.replace("TimeAcquired=",String.empty);
After just parse.
int mrt= int.parse(t);
I have a Socket communication in my Windows Phone app, but when I call it I can sometimes get a result, that looks like this
\0\0\0\0<RESULT><DATA>...</DATA></RESULT>\0
I want to remove the start and the end of it so I only get the XML, but what is the best way to do it?
I have thought about Regex, but I can not make it work :(
It sounds like a problem with your protocol, but to remove the \0 characters you could do a simple trimming of the string.
If your string has the actual \ and 0 characters in it then you could do the following:
var fixedData = receivedData.Trim(new[] { '\\', '0' });
And if the string starts with null characters (encoded as \0) then you could to:
var fixedData = receivedData.Trim(new[] { '\0' });
Both examples assume that the variable receviedData is a String containing your data.
I have not enough information to answer you correctly, so I will suggest the following :
You should try to map the data you are receiving from your socket to a serializable class.
And then you serialize the classObject to an XML document.
public class socketDataToMap
{
public string Data {get; set;}
}
and then
var ser = new XmlSerializer(typeof(socketDataToMap));
using (var reader = XmlReader.Create(yourSocketStream))
{
var deserializedObject = ser.Deserialize(reader) as socketDataToMap;
}
and then you serialize to an XML file. I see something like this for your problem.
If your result have to be XML and more characters(else \0) can be in start or end of your string, these code can be useful:
var start = inputString.IndexOf('<');
var end = inputString.LastIndexOf('>');
var result = inputString.Substring(start, end - start);
String.IndexOf Method (Char): Reports the zero-based index of the first occurrence of the specified Unicode character in this string.
String.LastIndexOf Method (Char): Reports the zero-based index position of the last occurrence of a specified Unicode character within this instance.
String.Substring Method (Int32, Int32): Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.
C#: I have a string that comes from a webpage's sourcecode:
<script type="text/javascript">
var itemsLocalDeals = [{"category":"HEALTHCARE SERVICES",
"dealPermaLink":"/deals/aachen/NLP-Deutschlandde
5510969","dealPrice":"399,00 \u20ac",..........
I do some things with that string, such as extracting the dealPrice and add it to a List<> (in the whole string are more than one dealPrice).
Is there a method to decode all "\u20ac" to their real character ("€")?
There are also other characters, so not only the €-Character has to be decoded.
When I debug my code and look at the local fields/variables the string contains not the "€"-Character but the escaped sequence "\\u20ac".
Something like myString.DecodeUnicodeToRealCharacters.
I'm writing the result to a (UTF-8)result.txt
Thanks alot!
P.S.: Unfortunately .Net 2.0 only...
You can use Regex.Unescape("\u20ac");
But better use a json parser since your string seems to be a json string(starting with [{"category":"HEALTHCARE SERVICES",.....)
public string DecodeUnicodeToRealCharacters(string s)
{
return Encoding.Unicode.GetString(Encoding.Unicode.GetBytes(s));
}
Can you please show the code you're using to write the text?
this one works just fine:
string str = "\u20ac";
using (StreamWriter sw = new StreamWriter(#"C:\trythis.txt", false, Encoding.UTF8)){
sw.Write(str);
}