I am generating an output on a webpage in a format l开发者_StackOverflowike this
({"1":"Jeff","2":"Tom","3":"Michael",})
For this, basically this is the code I am using
Response.Write("(" + "{");
//
for (Int32 i = 0; i < k.Length; i++)
{
Response.Write(Convert.ToString(k.GetValue(i)) + ",");
}
//
Response.Write("}" + ")");
Notice my output, after Michael" there is a comma which I do not want since this is the last vaue but this is appearing since ,
is in the for loop. How to prevent this/remove this last comma from appearing?
My output should be ({"1":"Jeff","2":"Tom","3":"Michael"})
(There's no comma after last value here)
Assuming k
is an array of strings
List<string> tokens = k.ToList<string>();
Response.Write("({" + String.join<string>(",", tokens) + "})");
Simplified and VB.Net, but i think you will get it:
Dim values As New List(Of String)(New String() {"1:Jeff", "2:Tom", "3:Michael"})
Dim result As String = "({" & String.Join(",", values.ToArray) & "})"
If k is a Collection like Array,List etc.
Depending on the number of iterations and how often this happens use StringBuilder instead.
StringBuilder sb = new StringBuilder();
for (Int32 i = 0; i < k.Length; i++)
{
sb.Append(",");
sb.Append(Convert.ToString(k.GetValue(i)));
}
if (sb.Length > 0) {
sb.Remove(0,1);
}
Response.Write(String.Format("({{{0}}})", sb.ToString()));
Another way is: However, it has to check every iteration.
StringBuilder sb = new StringBuilder();
for (Int32 i = 0; i < k.Length; i++)
{
if (sb.Length > 0) {
sb.Append(",");
}
sb.Append(Convert.ToString(k.GetValue(i)));
}
Response.Write(String.Format("({{{0}}})", sb.ToString()));
you can decrease your loop instead increase... like
for (Int32 i = k.Length; i > 0; i--)
and put: if (i == 1) removeComa;
Response.Write("(" + "{");
//
for (Int32 i = 0; i < k.Length; i++)
{
Response.Write(Convert.ToString(k.GetValue(i)) + (i == k.Length - 1 ? "" : ","));
}
//
Response.Write("}" + ")");
One of my favorite fixes for this is to use a prepend instead and only set comma as the seperator value after the first item (sorry for the VB):
Dim seperator As String = ""
For i As Integer = 0 To k.Length
Response.Write(seperator + Convert.ToString(k.GetValue(i)))
seperator = ","
Next
In your loop, simply use insert a "break" when the count reaches the last digit and that has been processed?
If you change how you output to write the first object in the collection then everyone after preceded by a comma it should work fine.
Response.Write("(" + "{");
//
Response.Write(Convert.ToString(k.GetValue(0)));
for (Int32 i = 1; i < k.Length; i++)
{
Response.Write("," + Convert.ToString(k.GetValue(i)));
}
//
Response.Write("}" + ")");
An alternative would be writing to a stringbuilder and outputting all but the last character
精彩评论