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
Related
I need to apply the following transformation to a string:
convert the string in byte[]
apply the sha256 function
encode the result in base64
I wrote the following code:
string codeRaw = "C0643778W.EUC06AG978W.EUFWELP2014-11-2153.50000GBP24.00000MWh/h10YCB-EUROPEU--12015-01-012015-01-31";
byte[] utiCodeByteArr = Encoding.UTF8.GetBytes(codeRaw);
byte[] hashByteArr = new SHA256Managed().ComputeHash(utiCodeByteArr);
string hash = Convert.ToBase64String(hashByteArr)
It works, but the result is a little bit different from was I should get: the string contains the chars '+', '/' and '=' instead of 'A', 'B' and 'C'.
"qWAIh1CgYAuvoRTGcvXKLBHC9UxRunSBRjRXlqhYh6gC" //expected result
"qW+Ih1CgYAuvoRTGcvXKLBHC9UxRunS/RjRXlqhYh6g=" //got result
I've solved with a replace
string hash = Convert.ToBase64String(hashByteArr)?.Replace("+", "A")?.Replace("/", "B")?.Replace("=", "C");
There is a better way to get the right string without using the replaces?
I don't like them.
The manual with the requirements say: "The APIs used are the ones provided by .NET framework", but it doesn't contains the source code: maybe there is a way to get immediately the ABC chars, but I miss it.
Thanks.
The provider sent me the source code: there was a replace as the one I did.
They forgot to wrote that information in the manual.
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 the following code but giving an error "Cannot implicitly convert type 'string' to 'char[]'"
char[] hTempFile = new char[300 + 1];
hTempFile ="";
A char[] is different to a string. If you intend to be an empty array, then:
hTempFile = new char[0];
or perhaps simply (if you add a few null-checks):
hTempFile = null;
There is also .ToCharArray() on a string, but that seems overkill here.
Frankly, for a file-name, it sounds like you should actually be using string here.
It looks like a C style string initialization, in C# it is best to avoid using char arrays for strings and use the string class instead.
string hTempFile = string.Empty;
What do you want to achieve? you have already defined hTempFile as type char[].
You cannot assign a string value to hTempFile .
You can use String.ToCharArray() to get array of char from string....If the string is empty like in your given example, the returned array is empty and has zero length....
hTempFile = "".ToCharArray();
It looks like you want to set hTempFile to an empty string -- or, more specifically, the C-string representation of an empty string. If that's the case, all you need to do is
hTempFile[0] = 0;
Since C-strings are null-terminated, placing a null byte in the first char of the array effectively empties the string.
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.