What is the difference when I convert integer to string like this way:
string str = "" + 1;
And
string str =1.ToString();
The first method is equivalent to string str = "" + 1.ToString(); and uses 2 intermediate strings before producing the result. That amounts to 3 strings total: an empty string, "1", and the result of the concatenation, which is also "1".
The second method doesn't use any intermediate string. It's also more readable and clearly expresses your intent (which is to convert the integer into a string).
With ToString() you assign a return value of the method. By using "" + 1 the ToString() method is called by the CLR.
See Automatic .ToString()?
int.ToString() is the tool for converting an integer into a string.
However, the C# allows you not to call this method when concatenating strings via plus operator, and the framework calls .ToString() instead of you.
Related
I know this question has been answered many times before however, I'm convinced the code I have is correct but isn't working correctly.
string total = ds.Tables[0].Rows[0][0].ToString();
string test = string.Format("{0:N}", total);
lbl_totalValue.Text = test;
This code isn't adding the commas into my value like it desire it to.
Can anyone see why?
When you put
string total = ds.Tables[0].Rows[0][0].ToString();
it means implicit G ("General") format string
string total = ds.Tables[0].Rows[0][0].ToString("G");
Do not format prematurely:
var total = ds.Tables[0].Rows[0][0]; // Value from table
string test = string.Format("{0:N}", total); // Format total with "N" format string
Your code is trying to format a string. If the DataTable contains a number you can pass the format specifier to ToString(), eg
var test=ds.Tables[0].Rows[0][0].ToString("N");
Or store the contents in a local variable and use String.Format :
var total = ds.Tables[0].Rows[0][0];
string test = string.Format("{0:N}", total);
If the datatable contains a string though, you'd have to parse it to a numeric type first
You have to use the string.Format with a number type, instead of string. In this case, the variable total is a string, it must be a number.
There are 8 overloads for the Strig.Format method. You are using this specific one: Format(String, Object) in which you pass a String value as argument of the second parameter. This is because you are using a string variable (total) to assign the value from the dataset in:
string total = ds.Tables[0].Rows[0][0].ToString();
Besides you are using .ToString() to retrieve it as a String.
If you are using SQL Server as data source to your ds dataset and you are certain about the SQL data type then you can assign that value directly to a variable with the corresponding C# type. To put it in a different way, SQL data types are mapped to C# data types.
If you are not sure about the C# data type of ds.Tables[0].Rows[0][0] then you could simply do the following:
Object total = ds.Tables[0].Rows[0][0];
string test = string.Format("{0:N}", total);
lbl_totalValue.Text = test;
And this way you literally use the Format(String, Object) overload of String.Format.
I have looked around for this, but I'm not sure it's possible with string interpolation (I'm using VS2015).
string sequenceNumber = $"{fieldValuePrefix.ToUpper()}{separator}{similarPrefixes + 1:D4}";
Is there any way to make D4 a variable ? Some say yes, some no. Apparently, VS2015 C#6.0 is able to do it.
This works, it will return a string like WMT-0021, depending on fieldValuePrefix (WMT), separator (-) and the value of similarPrefixes (20). But I'd like the "D4" part to be a method argument instead of hardcoded in there.
Any ideas ?
You can, but you have to use explicit ToString call like this:
string format = "D4";
string sequenceNumber =
$"{fieldValuePrefix.ToUpper()}{separator}{(similarPrefixes + 1).ToString(format)}";
I have a String I want to get the index of the "id:" i.e the id along with the double quotes.
How I am supposed to do so inside C# string.IndexOf function?
This will get the index of the string you want:
var idx = input.IndexOf("\"id:\"");
if you wanted to pull it out you'd do something like this maybe:
var idx = input.IndexOf("\"id:\"");
var val = input.Substring(idx, len);
where len is either a statically known length or also calculated by another IndexOf statement.
Honestly, this could also be done with a Regex, and if an example were available a Regex may be the right approach because you're presumably trying to get the actual value here and it's presumably JSON you're reading.
" is an escape sequence
If you want to use a double quotation mark in your string, you should use \" instead.
For example;
int index = yourstring.IndexOf("\"id:\"");
Remember, String.IndexOf method gets zero-based index of the first occurrence of the your string.
This is a simple approach: If you know double quote is before the Id then take index of id - 1?
string myString = #"String with ""id:"" in it";
var indexOfId = myString.IndexOf("id:") - 1;
Console.WriteLine(#"Index of ""id:"" is {0}", indexOfId);
Reading between the lines, if this is a JSON string, and you have .NET 4 or higher available, you can ask .NET to deserialize the string for you rather than parsing by hand: see this answer.
Alternatively you might consider Json.NET if you're working very heavily with JSON.
Otherwise, as others note, you need to escape the quotes, so for example:
text.IndexOf("\"id:\"")
text.IndexOf(#"""id:""")
or for overengineered legiblity:
string Quoted(string text)
{
return "\"" + text + "\""; // generates unnecessary garbage
}
text.IndexOf(Quoted("id:"))
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.
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
how can I convert String to Int ?
Hi,
I have the following problem converting string to an integer:
string str = line.Substring(0,1);
//This picks an integer at offset 0 from string 'line'
So now string str contains a single integer in it. I am doing the following:
int i = Convert.ToInt32(str);
i should be printing an integer if I write the following statement right?
Console.WriteLine(i);
It compiles without any error but gives the following error on runtime:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.
Any help please?
Rather than using Convert.ToInt32(string) you should consider using Int32.TryParse(string, out int) instead. The TryParse methods are there to help deal with user-provided input in a safer manner. The most likely cause of your error is that the substring you are returning has an invalid string representation of an integer value.
string str = line.Substring(0,1);
int i = -1;
if (Int32.TryParse(str, out i))
{
Console.WriteLine(i);
}
FormatException
value does not consist of an optional
sign followed by a sequence of digits
(0 through 9).
The exception that is thrown when the
format of an argument does not meet
the parameter specifications of the
invoked method.
You can use Int32.TryParse if you don't want to generate an exception like this.
Int32.TryParse: Converts the string representation of
a number to its 32-bit signed integer
equivalent. A return value indicates
whether the operation succeeded.
It's entirely possible there is some whitespace in there. Try running something akin to trim() (I'm not sure what language you're in) that will strip the white space. Also, try printing out the string to make sure you actually have the right part of it. We've all done that :)
It's likely that your input is not a valid format. Try this instead. If the number is not valid, it should output an error.
Keep in mind that the string should consist of an optional sign followed by a number.
string line = "23"; // or whatever.
string str = line.Substring(0,1);
int i = 0;
if (Int32.TryParse(str, out i)) {
Console.WriteLine(i);
} else {
Console.WriteLine ("Error converting '" + line + "', '" + str + "'.");
}
One thing you may be seeing is the user entering "-1" for example. If you do the substring(0,1) on that, you'll only get "-" which isn't really valid.
Are you sure that the value returned in str is an int, set a debug point if your using visual studio. Ive got a feeling your problem maybe that your not actually returning an integer. Try:
line.Trim().Substring(0,1);
This will remove any whitespace.