简体   繁体   English

修剪字符串末尾的最后一个字符

[英]Trim the last character at the end of string

I have a loop that is creating a string until the end of the file.我有一个循环创建一个字符串,直到文件结束。 Depending on how many products I have at the time.取决于我当时有多少产品。 I need to trim the last comma at the end.我需要在最后修剪最后一个逗号。

I get:我得到:

{ sku: '6200', display_name:'Product 1', unit_price: 497.37, qty: 1 },  
{ sku: '2344', display_name:'Product 2', unit_price: 824.21, qty: 1 },

I need:我需要:

{ sku: '6200', display_name:'Product 1', unit_price: 497.37, qty: 1 },  
{ sku: '2344', display_name:'Product 2', unit_price: 824.21, qty: 1 }

Loop:环形:

<%
set rsheadercart = db.execute(sqlheadercart)
    if not rsheadercart.eof then 
        do until rsheadercart.eof 




            items = items & " { sku: '" & rsheadercart("ten_digit_part_number") & "',"
            items = items & " display_name:'" & rsheadercart("part_name") & "',"
            items = items & " unit_price: " & rsheadercart("price") & ","
            items = items & " qty: " & rsheadercart("quantity") & " }, "


        rsheadercart.movenext
        loop 
        %>
<%
end if 
%>

Have found the simplest way over the years is to let the loop generate the extra character than just trim it after the execution of the loop using Left() .多年来发现最简单的方法是让循环生成额外的字符,而不是在循环执行后使用Left()修剪它。

After your loop add;在你的循环添加之后;

items = Left(items, Len(items) - 1)

This way avoids having to add a load of logic into the loop to handle the edge cases unnecessarily.这种方式避免了在循环中添加大量逻辑来处理不必要的边缘情况。

Move your comma to the beginning of the loop and put it in a conditional statement so that it isn't executed at the first iteration将逗号移到循环的开头并将其放在条件语句中,以便在第一次迭代时不会执行

do until rsheadercart.eof 

    If items <> "" then 
       items = items & ","
    End If     

    items = items & " { sku: '" & rsheadercart("ten_digit_part_number") & "',"
    items = items & " display_name:'" & rsheadercart("part_name") & "',"
    items = items & " unit_price: " & rsheadercart("price") & ","
    items = items & " qty: " & rsheadercart("quantity") & " } "

rsheadercart.movenext
loop 

In cases like that I often use the Join method在这种情况下,我经常使用Join方法

dim itemList 
set itemList = CreateObject("System.Collections.ArrayList")
do until rsheadercart.eof 
    dim item       
    item = " { sku: '" & rsheadercart("ten_digit_part_number") & "',"
    item = item & " display_name:'" & rsheadercart("part_name") & "',"
    item = item & " unit_price: " & rsheadercart("price") & ","
    item = item & " qty: " & rsheadercart("quantity") & " } "
    itemList.Add item
    rsheadercart.movenext
loop 
items = Join(itemList.ToArray,",")

If you don't want to use an Arraylist, you can do the same with an plain array, but you would have to redim it each iteration.如果您不想使用 Arraylist,您可以对普通数组执行相同操作,但每次迭代都必须重新调整它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM