×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Best way to remove the trailing comma (or whatever) from a string?
4

Best way to remove the trailing comma (or whatever) from a string?

Best way to remove the trailing comma (or whatever) from a string?

(OP)
Curiosity getting the better of me... and knowing I won't be roasted by the current community... I hope. happy shades

Assuming we have assembled a string like "1234,123,198,678," what are your favourite ways to remove the trailing comma?

CODE

m.STRING = LEFT(m.STRING,LEN(m.STRING)-1) 

Is ok if you are confident there is a trailing comma... Mike recently hinted that PadR() might be useful.

Regards

Griff
Keep Smileing

There are 10 kinds of people in the world, those who understand binary and those who don't.

I'm trying to cut down on the use of shrieks (exclamation marks), I'm told they are !good for you.

There is no place like G28 X0 Y0 Z0

RE: Best way to remove the trailing comma (or whatever) from a string?

Quote:

Mike recently hinted that PadR() might be useful

Did I? If so, that was clearly a mistake. The function is RTRIM():


lcString = RTRIM(lcString, ",")


And no harm is done if it happens that there is no trailing comma.

(I have now corrected thread184-1819024: bulk sms in vfp9.)

Mike

__________________________________
Mike Lewis (Edinburgh, Scotland)

Visual FoxPro articles, tips and downloads

RE: Best way to remove the trailing comma (or whatever) from a string?

(OP)
That is pretty neat, I was not aware of the option to include one or more characters.

Regards

Griff
Keep Smileing

There are 10 kinds of people in the world, those who understand binary and those who don't.

I'm trying to cut down on the use of shrieks (exclamation marks), I'm told they are !good for you.

There is no place like G28 X0 Y0 Z0

RE: Best way to remove the trailing comma (or whatever) from a string?

Hi,

RTRIM() is the way to go

you may even specify all the characters you want to be removed from the right edge

lcStr = "2345,6667,88.,bab"

? RTRIM(lcStr, ".",",","a","b")

hth

MarK

RE: Best way to remove the trailing comma (or whatever) from a string?

Quote:

I was not aware of the option to include one or more characters.

That option was only introduced in VFP 9.0. Before that, you could only use the function to remove trailing spaces.

Mike

__________________________________
Mike Lewis (Edinburgh, Scotland)

Visual FoxPro articles, tips and downloads

RE: Best way to remove the trailing comma (or whatever) from a string?

OK, here's something else to wrap your brains around.

Suppose you have one or more comma inside a string, perhaps like this:

HELLO,,,WORLD,FROM,,,,TEK-TIPS

You want to eliminate all those commas, replacing each substring of commas with a single space, like so:

HELLO WORLD FROM TEK-TIPS

How would you go about that with the minimum amount of code?

Mike

__________________________________
Mike Lewis (Edinburgh, Scotland)

Visual FoxPro articles, tips and downloads

RE: Best way to remove the trailing comma (or whatever) from a string?

BTW Help says RTRIM() is identical to TRIM()

Steve

RE: Best way to remove the trailing comma (or whatever) from a string?

Quote:

Help says RTRIM() is identical to TRIM()

That's right. The reason is historical. Back in dBASE days, they never thought we would ever want to trim the left-most spaces. So we had just plain TRIM(), which trimmed the right-most spaces. When LTRIM() was later introduced, they added RTRIM() to balance things out, as it were. But of course they kept the old TRIM(), so as not to break compatibility.

Personally, I always use RTRIM() in preference to TRIM() for the simple reason that it is more explicit. I expect most other developers do too.

Mike

__________________________________
Mike Lewis (Edinburgh, Scotland)

Visual FoxPro articles, tips and downloads

RE: Best way to remove the trailing comma (or whatever) from a string?

Well, I would divide this into 3 camps:

1. Build the string with the necessary commas only
2. Use comma prefixed before each item and finally use SUBSTR from the second position.
3. Add items with ccomma suffix and finally remove the surplus comma with LEFT() or RTRI/TRIM.

Assume there is a dbf or curssro alias items with an item field that's varchar and so has trimmed items (no trailing spaces as you have with a normal char field).


1. with IIF

CODE

Local lcCSV
lcCSV=''
Select items
scan
   lcCSV = m.lcCSV+IIF(lcCSV=='','',',')+items.item
endscan 

2. prefix and SUBSTR

CODE

Local lcCSV
lcCSV=''
Select items
scan
   lcCSV = m.lcCSV+','+items.item
endscan
lcCSV = Substr(m.lcCSV,2) 

3. suffix and TRIM

CODE

Local lcCSV
lcCSV=''
Select items
scan
   lcCSV = lcCSV+items.item+','
endscan
lcCSV = RTRIM(m.lcCSV,',') 

And all of them have their negative point.
1. An IIF for every item
2. and 3: A final string operation.

But it's also pointless to rant about this necessary last operation in case 2 and 3, as every item you append with the assignment lcCSV = lcCSV + does nneed to allocate enough memeory for the overall string, and copies over lcCSV plus the item into it. VFP has no thing like C#'s stringbuilder class. And though VFP is programmed in C++ it also has no pointer to do tricks with, at least you don't have hands on it within VFP itself. There also isn't a function like PHPs implode().

There are surely more ways to do it
4. like 1, but without IIF:

CODE

Local lcCSV, lcSeparator
Store '' To lcCSV, lcSeparator
Select items
scan
   lcCSV = m.lcCSV+lcSeparator+items.item
   lcSeprator = ','
endscan 
Now there's no IIF, but an assignment that would be suffiient, if it's done once instead of every iteration

5. like 1 but through special handling of first element

CODE

Local lcCSV
Select items
Go Top
lcCSV = items.item
Skip 1
Scan Rest
   lcCSV = m.lcCSV+','+items.item
Endscan 

Now you can play with these and special cases like extremely many items or no items at all, etc. etc.

But you can't tell me that you can't think of any way on your own, at least to create the string with a surplus comma at the start or end. And then it's really just a short visitation of the help to look up how to get substrings, which functions exist for that, like LEFT, RIGHT, SUBSTR, or how you can use TRIM/RTRIM/LTRIM/ALLTRIM. Also ALLTRIM allows specifying other characters to trim away than whitespace.

It does really not play any mentionable role to do things the one or other way. If you have extremely many elements it would turn out to be better to create partial lists and concatenate them as a last step. If you have 1 million elements you would make 999.999 copies in average half the string length, and that would hurt the performance, but it would be a problem no matter which of the three major methods you choose. And the last step to remove the comma will never be a major part of the operation.

Chriss

RE: Best way to remove the trailing comma (or whatever) from a string?

(OP)
I might do this, but I am sure there is an array function too

CODE

CLEAR

? CLEARSTRING("HELLO,,,WORLD,FROM,,,,,,,,,TEK-TIPS",",")

FUNCTION CLEARSTRING
	PARAMETERS m.STRING,m.STRDELIM
	PRIVATE m.STRING,m.STRDELIM,m.STRING2,m.MAXWORDS,m.INDEX
	m.MAXWORDS = GETWORDCOUNT(m.STRING,m.STRDELIM)
	m.STRING2 = ""
	FOR m.INDEX = 1 TO m.MAXWORDS
		m.STRING2 = m.STRING2+GETWORDNUM(m.STRING,m.INDEX,m.STRDELIM)+" "
	NEXT
	RETURN(RTRIM(m.STRING2)) 

Regards

Griff
Keep Smileing

There are 10 kinds of people in the world, those who understand binary and those who don't.

I'm trying to cut down on the use of shrieks (exclamation marks), I'm told they are !good for you.

There is no place like G28 X0 Y0 Z0

RE: Best way to remove the trailing comma (or whatever) from a string?

Mike,

about your task to fix a string like "HELLO,,,WORLD,FROM,,,,TEK-TIPS".
I guess you think about the foxtools.fll, which has that function for it:

CODE

lcCSV = "HELLO,,,WORLD,FROM,,,,TEK-TIPS"

Set Library To Home()+"foxtools.fll"
lcCSV = Reduce(lcCSV,',')

? lcCSV 

It's replaceing any number of commas with one space, though, so at the end you get HELLO WORLD FROM TEK-TIPS.

Now it would depend on whether single items (i.e two words or more, like full names) can contain spaces. If not, you could now replace every space with a comma:

CODE

lcCSV = "HELLO,,,WORLD,FROM,,,,TEK-TIPS"

Set Library To Home()+"foxtools.fll"
lcCSV = Chrtran(Reduce(lcCSV,','),' ',',')

? lcCSV 

Well, if you have spaces within items, what would work is first replacing them with something else to protect them as is.

CODE

lcCSV = "Mike Lewis,,,Chirs Miller,Steve Meyerson,,,,TEK TIPS"

Set Library To Home()+"foxtools.fll"
lcCSV = Chrtran(Reduce(ChrTran(lcCSV,' ',Chr(255)),','),' '+Chr(255),', ')

?lcCSV 
And the only thing to ensure as prerequisite for this to not break anything is to have no CHR(255) in your items. Thats ΓΏ and also a letter, so perhaps use some other character as temporary space replacement, like chr(7), which is the ANSI character for playing "ding.wav" and so usually is not within any string items.

Chriss

RE: Best way to remove the trailing comma (or whatever) from a string?

How about this ...

CODE --> Foxpro

s="HELLO,,,WORLD,FROM,,,,,,,,,TEK-TIPS"
DO WHILE AT(",,",s)>0
  s=STRTRAN(s,",,",",")
ENDDO
? s 

RE: Best way to remove the trailing comma (or whatever) from a string?

Oops, I didn't notice that we wanted ALL commas gone, here is the updated code:

CODE --> VFP

s="HELLO,,,WORLD,FROM,,,,,,,,,TEK-TIPS"
DO WHILE AT(",,",s)>0
  s=STRTRAN(s,",,",",")
ENDDO
s=STRTRAN(s,","," ")
? s 

RE: Best way to remove the trailing comma (or whatever) from a string?

Quote (jwilson)

I didn't notice that we wanted ALL commas gone, here is the updated code:

I'm guilty of the same misunderstanding. Aa the main topic was comma separated lists.
Indeed Reduce() of foxtools does that and wouldn't need a while loop. It would help to have a Reduce function in which you could also specify what character you want to end up with, too. So you could decide to get a string with single spaces or a comma separated list or whatever you want.

Chriss

RE: Best way to remove the trailing comma (or whatever) from a string?

How about this:

CODE -->

t="HELLO,,,WORLD,FROM,,,,TEK-TIPS"
?t
HELLO,,,WORLD,FROM,,,,TEK-TIPS
?STRTRAN(STRTRAN(STRTRAN(t,",,",","),",,",","),","," ")
HELLO WORLD FROM TEK-TIPS 
Of course, more "," would require additional STRTRAN ...

I came looking for another answer and got pulled into Mike's exercise, DOH!

msc wink

RE: Best way to remove the trailing comma (or whatever) from a string?

Some good solutions there. But there is a simpler way. In fact, Chris hinted at what I had in mind:

CODE -->

SET LIBRARY TO "foxtools.fll"
? REDUCE("HELLO,,,WORLD,FROM,,,,TEK-TIPS", ",") 

EDIT: Sorry, I missed out the second parameter to REDUCE(). I have now added it - see highlight).

Mike


__________________________________
Mike Lewis (Edinburgh, Scotland)

Visual FoxPro articles, tips and downloads

RE: Best way to remove the trailing comma (or whatever) from a string?

Mike Lewis,

you forgot to ask REDUCE to reduce one or multiple commas to spaces. The REDUCE as you posted it (REDUCE("HELLO,,,WORLD,FROM,,,,TEK-TIPS")) does not remove anything.
I see you corrected your post.

Using REDDUCE for other characters also has its downside, as already said:

CODE

? REDUCE("Ssssnailssss","Ss") 
This outputs " nail ".

If you'd like to get "Snails" as a result you'd need to replace the first space with "S" and the last one with "s".
More generally said, if you use REDUCE to reduce other characters than whitespace characters and reduce multiple characters, it becomes harder to reduce them to single instances of themselves, as REDUCE always reduces what it reduces to single spaces. So its main intent is to remove surplus whitespace, as could be found in HTML, for example, or in source code. Though in case of source code reduce should make a difference between spaces in string delimiters vs the rest of the code, where any number of spaces have the same meaning as a single space.

Chriss.

RE: Best way to remove the trailing comma (or whatever) from a string?

Nice - did not realize REDUCE was a function. I need to read more

thanks!

RE: Best way to remove the trailing comma (or whatever) from a string?

REDUCE only can be used once you SET LIBRARY TO FOXTOOLS.FLL. Most functions of this library are already part of VFP or very similarly integrated into VFP. One of the few useful things of the FLL is Reduce, and some functions regarding the Windows clipboard, so you can work with more than just _CLIPTEXT.

Chriss

RE: Best way to remove the trailing comma (or whatever) from a string?

Thanks, Chris. I should have specified a comma as the second parameter to REDUCE(). I have now corrected it - see above.

Of course, you can remove any character in this way, not just commas. You can also specify multiple characters in the second parameter, in which case they are treated independently, not as a single multi-character string.

Mike

__________________________________
Mike Lewis (Edinburgh, Scotland)

Visual FoxPro articles, tips and downloads

RE: Best way to remove the trailing comma (or whatever) from a string?

For anyone not familiar with Foxtools, you can find out more by perusing the Help file, FOXTOOLS.HLP, which is in the main VFP9 directory.

In fact, the only other function I have used recently is RGBComp(). Most of the other useful ones are now native to VFP.

Mike

__________________________________
Mike Lewis (Edinburgh, Scotland)

Visual FoxPro articles, tips and downloads

RE: Best way to remove the trailing comma (or whatever) from a string?

Yes, and using this in production (within your EXE) of course means also providing foxtools.fll, which you're allowed to redistribute, too.
One SET LIBRARY and you have a slightly extended VFP language.

You won't get intellisense help when writing functions available through foxtools. That makes it a bit less pleasant than native functions. The necessary info for intellisense could be added to foxcode.dbf.

And now, if you're thinking this can be used to extend VFP language. Well, yes, but with functions only, an FLL can't define/declare new VFP commands, that's not foreseen in the structure of an FLL, especially the FoxInfo struture, that's described in the help, too: https://www.vfphelp.com/vfp9/_5wn12p9el.htm

This FoxInfo structre only can list functions and their parameterization.

Chriss

RE: Best way to remove the trailing comma (or whatever) from a string?

Of course REDUCE is no solution to the thread main title and question.

CODE

? REDUCE(",1234,123,198,678,",",") 
output: 1234 123 198 678

If you might not know or care if your list string has a leading or a trailing commma or both, here's how ALLTRIM trims off commas from both ends and keeps the middle ones:

CODE

? ALLTRIM('1234,123,198,678,',',')
? ALLTRIM(',1234,123,198,678',',')
? ALLTRIM(',1234,123,198,678,',',') 

All three variants result in: 1234,123,198,678. Well, and of course if the list already is correct, such an ALLTRIM does nothing, just like ALLTRIM on a string with neither leading nor trailing whitespace does anything.

Chriss

RE: Best way to remove the trailing comma (or whatever) from a string?

And here's a (drastical!) demonstration of how slow string concatenation is, to showcase how much importance is on the length of a list you build instad of what function exactly you use for the last step of removing a surplus comma:

CODE

Clear
Local s, t
s=''
t=Seconds()
t1=m.t
Do While Len(s)<16777384
   s=m.s+' '
   If Len(m.s)%10000=0
      ? Textmerge("<<Len(m.s))>>, average <<Round(Len(m.s)/(Seconds()-m.t),0)>> spaces per second, last 10000 spaces took <<Seconds()-m.t1>> seconds.")
      t1 = Seconds()
   Endif
EndDo 

The obvious solution to get n spaces in a string is to use SPACE(n) instead of a while loop, but that's not the point. The point is to understand why adding just a single space to a string takes longer and longer, the longer the string is.

And I wouldn't have expected how high the performance degrades. It all plays a neglectible role from strings in the range of a few KB, but keep that in mind if you need to concatenate a lot of items.

Chriss

RE: Best way to remove the trailing comma (or whatever) from a string?

Using Regular Expression replacement:

CODE --> VFP

LOCAL RegX AS VBScript.RegExp

m.RegX = CREATEOBJECT("VBScript.RegExp")

m.RegX.Global = .T.

m.RegX.Pattern = "([^\,\s]*)([\,\s]*)"

? TRIM(m.RegX.Replace("HELLO,,,WORLD,FROM,,,,TEK-TIPS", "$1 ")) 

(also, making sure there won't be duplicate spaces inside the string).

RE: Best way to remove the trailing comma (or whatever) from a string?

Wow, been an RTRIM() user since Fox 2.0 and never realized that. I have used ALLTRIM() mostly just to get rid of padded characters on either side for decades, but RTRIM() accepting more than one parameter... I guess I just never read the help file on that function. I assume LTRIM() allows the same thing.

Best Regards,
Scott
MSc ISM, MIET, MASHRAE, CDCAP, CDCP, CDCS, CDCE, CTDC, CTIA, ATS, ATD

"I try to be nice, but sometimes my mouth doesn't cooperate."

RE: Best way to remove the trailing comma (or whatever) from a string?

Hi Scott

All the 4 - TRIM, ALLTRIM, LTRIM and RTRIM accept more than 1 parameter - at least in VFP9. In addition you can specify them to be case-sensitive. Please have a look at the help file

hth

MarK

RE: Best way to remove the trailing comma (or whatever) from a string?

Quote (Griff)

what are your favourite ways to remove the trailing comma?

FWIW my favorite and most used way is to avoid placing the comma at the end of the string in the first place.

In general, I start building the string with the first item (without a comma) followed by the rest of the items in the string, each PRECEDED by a comma.

The "rest" of the items might be from looping through an array (e.g. field names) or whatever.

Steve

RE: Best way to remove the trailing comma (or whatever) from a string?

Steve, that corresponds to my sample 5, totally valid. You can SKIP 1 and SCAN REST for starting with the second item in a cursor, or you loop for lnI=2 to alen(array) after you started with the first array element. Starting with the second element (or second row) of an array just isn't possible elegantly in a For each loop, but of course instead of starting with an empty string, you can start with the first item and then precede a comma before every further item.

It rarely makes sense to create a list, if there are no items, but whenever an empty list also can make sense (as optional parameter, for example), you should also cover that. For that corner case you need special caution about knowing you have at least 1 element, a normal SCAN or FOR EACH loop covers that case without special handling, and you end with what you started: An empty string. Because if you start a SCAN loop on EOF() you actually don't ever enter the loop body and execute it, the loop ends before it begins, likewise a FOR loop with a final value lower than the initial also does end before it begins.

Chriss

RE: Best way to remove the trailing comma (or whatever) from a string?

Quote:

Wow, been an RTRIM() user since Fox 2.0 and never realized that

Don't feel bad about that, Scott. The second parameter was only added in VFP 9.0. Before that, the only thing you could trim was spaces.

Mike

__________________________________
Mike Lewis (Edinburgh, Scotland)

Visual FoxPro articles, tips and downloads

RE: Best way to remove the trailing comma (or whatever) from a string?

Quote (Chris)

Steve, that corresponds to my sample 5, totally valid.

Sorry, Chris. Didn't read close enough. bigglasses

Steve

RE: Best way to remove the trailing comma (or whatever) from a string?

Mike,
Well THAT explains it! You know, when you spend 25+ years with a function, and you "know how it works", so easy to overlook the addition of some new capability in it. I mean, how often do you read the Help file for a function you "already know"? :)

That said, I don't know when I would need it. ><

Best Regards,
Scott
MSc ISM, MIET, MASHRAE, CDCAP, CDCP, CDCS, CDCE, CTDC, CTIA, ATS, ATD

"I try to be nice, but sometimes my mouth doesn't cooperate."

RE: Best way to remove the trailing comma (or whatever) from a string?

That's why we wrote the "What's New" books, to gather all the new stuff in one place. Even without those, the Help file has always had "What's New" sections to let you quickly learn what has changed.

Tamar

RE: Best way to remove the trailing comma (or whatever) from a string?

Quote (Scott24x7)

That said, I don't know when I would need it.

Do you realize I posted ALLTRIM with that additional parameter can be used as a universal solution to remove a surplus comma, no matter if it's a prefix or suffix comma. See my post from 29 Nov 22 21:10.

So actually it's usable as the answer to the main question of Griff. If that's of no use to you, then you may not ever create a comma separated items list or do it without surplus commas. Whatever, the way this additional parameter works is not only to change from whitespace to any other character, you can trim off any group of characters, and that can be useful for many kinds of operations, it's not always just whitespace that's unwanted.

Chriss

RE: Best way to remove the trailing comma (or whatever) from a string?

Tamar,
Yeah, and I read them when they came out, but I have big "gap years" between when I use VFP, and when I'm dormant. I went into developer retirement for 15 years, came back out, and picked VFP back up again around 2014. Since then I'm in and out. But in fairness, as I mentioned, the way I develop otherwise, I don't think I'd really ever use this extra parameter.
I do also watchin the auto help, where it tells you want parameters are used within the function as you type them, and I still never noticed this. I usually only use ALLTRIM anyway, anything else would have a test for length, and I'd likely use SUBSTR to get rid of unwanted characters.

Best Regards,
Scott
MSc ISM, MIET, MASHRAE, CDCAP, CDCP, CDCS, CDCE, CTDC, CTIA, ATS, ATD

"I try to be nice, but sometimes my mouth doesn't cooperate."

RE: Best way to remove the trailing comma (or whatever) from a string?

I think the question was to fix the string "HELLO,,,WORLD,FROM,,,,TEK-TIPS". Seems to me this can be done with a single line of code:

CODE -->

?CHRTRAN("HELLO,,,WORLD,FROM,,,,TEK-TIPS", ",", " ") 

Which replaces all commas with a space, yielding:

HELLO WORLD FROM TEK-TIPS (the extra spaces are being removed by the HTML display...)

If the problem is to remove the extra spaces as well, thus leaving a single space separating each word, then VFP does not have a native function to perform that task. The use of the REDUCE function in the FoxTools FLL would be the answer in addition to the CHRTRAN function.

CODE -->

SET LIBRARY TO foxtools.fll ADDITIVE
?REDUCE(CHRTRAN("HELLO,,,WORLD,FROM,,,,TEK-TIPS", ",", " "), " ") 


Greg

RE: Best way to remove the trailing comma (or whatever) from a string?

And just for the benefit of anyone not familiar with this, keep in mind that you only need to do SET LIBRARY once during the session. Once you have established a library file (that is, an FLL), it will stay in force until the end of the session or until you override it with a different library. (The ADDITIVE keyword is also supported.)

Mike

__________________________________
Mike Lewis (Edinburgh, Scotland)

Visual FoxPro articles, tips and downloads

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close