473,396 Members | 2,108 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

How to replace last comma with 'and' or '&' in a string with multiple commas ?

Hello everybody
Thank you all for helping others.
I have a very simple question that how can we replace only last comma with 'and' in string, which has got multiple commas?
Suppose we have a sentence "I like Banana, Orange, Grapes, Mango in fruits". I have tried Replace() function but that put 'and' in place of every comma, which is fine if there are only two items. But I want that this sentence must be converted to "I like Banana, Orange, Grapes and Mango in fruits", replacing only the last comma, when there are more than two items and replace the only comma in case when there are only two items.
Hope I have made my question understandable.
Nov 26 '13 #1

✓ answered by ADezii

  1. I would take a much different approach to solve this problem:
    Expand|Select|Wrap|Line Numbers
    1. Public Function fProcessString(strString As String) As String
    2. Dim varSplit As Variant
    3. Dim strBuild As String
    4.  
    5. varSplit = Split(strString, ",")
    6.  
    7. 'Determine how many Items are seperated by Commas
    8. Select Case UBound(varSplit)
    9.   Case 0
    10.     fProcessString = strString      'Return String
    11.   Case 1                            '1 Comma
    12.     fProcessString = varSplit(LBound(varSplit)) & " and " & varSplit(UBound(varSplit))
    13.   Case Else
    14.     strBuild = Left$(strString, InStrRev(strString, ",") - 1)
    15.     strBuild = strBuild & " and " & Mid$(strString, InStrRev(strString, ",") + 1)
    16.       fProcessString = strBuild
    17. End Select
    18. End Function
    19.  
  2. Sample Function Calls:
    Expand|Select|Wrap|Line Numbers
    1. Debug.Print fProcessString("Bananas")
    2. Debug.Print fProcessString("I like Bananas, Grapes")
    3. Debug.Print fProcessString("I like Bananas, Grapes, Pineapples")
    4. Debug.Print fProcessString("I like Bananas, Grapes, Pineapples, Peaches, Apricots")
    5.  
  3. Results:
    Expand|Select|Wrap|Line Numbers
    1. Bananas
    2. I like Bananas and  Grapes
    3. I like Bananas, Grapes and  Pineapples
    4. I like Bananas, Grapes, Pineapples, Peaches and  Apricots

13 4224
zmbd
5,501 Expert Mod 4TB
"I like Banana, Orange, Grapes and Mango in fruits"
vs
"I like Banana, Orange, Grapes, and Mango in fruits"
For most people, the last comman should remain in the list prior to the final and/or/conjuctive.

----------
COMMAS
A standard use for commas is to separate the items in a series: “cats, dogs, and gerbils.” Authorities differ as to whether that final comma before the “and” is required. Follow the style recommended by your teacher, editor, or boss when you have to please them; but if you are on your own, I suggest you use the final comma. It often removes ambiguities.
----------
So unless you have a teacher or editor that doesn't like the final comma, I would not be doing this.

This is very much like a homework problem.
So instead of simply posting the code I used to solve something along the same lines, I'll describe the logic.

As for finding the final comma in a sentence:
use the instr() function and the len() function.
do Loop
Instr() Find the first occurance
If the returned is non-zero then add one to the position returned, if > len then the position returned is your last comma else use the new increment as the starting point for your instring.
If the position returned is zero and the last returned was less than the len() of the string then the last position returned was the final comma
use the replace function using the optional start postion at the last instring
Replace Function

Please post the code you have come up with... at that point I'll be happy to help optimize it.
Nov 26 '13 #2
Am I missing something? I would think you could use the instrRev() function to locate the position of the last comma?
Nov 27 '13 #3
zmbd
5,501 Expert Mod 4TB
nope, instrRev() could be used... I forget about that one as it's fairly new to the scene (well for me anyway... guess it was first available with ACC2000; however I didn't start really considering it until just recently as all of the old ACC97 databases at my company have finally been forced to move to ACC2010 (evil laugh).)
Nov 27 '13 #4
NeoPa
32,556 Expert Mod 16PB
I would think you could use the InStrRev() function to locate the position of the last comma?
Indeed you could. That would be the most straightforward approach.

NB. When Z says Nope, he means you aren't missing anything. Not that your suggestion was wrong.

PS. I would add that, as a native of England, I find it most common here to omit the last comma from a sentence when the "and" or "or" is used. The alternative, proposed by Z, is often referred to as "The Oxford Comma".
Nov 27 '13 #5
ADezii
8,834 Expert 8TB
  1. I would take a much different approach to solve this problem:
    Expand|Select|Wrap|Line Numbers
    1. Public Function fProcessString(strString As String) As String
    2. Dim varSplit As Variant
    3. Dim strBuild As String
    4.  
    5. varSplit = Split(strString, ",")
    6.  
    7. 'Determine how many Items are seperated by Commas
    8. Select Case UBound(varSplit)
    9.   Case 0
    10.     fProcessString = strString      'Return String
    11.   Case 1                            '1 Comma
    12.     fProcessString = varSplit(LBound(varSplit)) & " and " & varSplit(UBound(varSplit))
    13.   Case Else
    14.     strBuild = Left$(strString, InStrRev(strString, ",") - 1)
    15.     strBuild = strBuild & " and " & Mid$(strString, InStrRev(strString, ",") + 1)
    16.       fProcessString = strBuild
    17. End Select
    18. End Function
    19.  
  2. Sample Function Calls:
    Expand|Select|Wrap|Line Numbers
    1. Debug.Print fProcessString("Bananas")
    2. Debug.Print fProcessString("I like Bananas, Grapes")
    3. Debug.Print fProcessString("I like Bananas, Grapes, Pineapples")
    4. Debug.Print fProcessString("I like Bananas, Grapes, Pineapples, Peaches, Apricots")
    5.  
  3. Results:
    Expand|Select|Wrap|Line Numbers
    1. Bananas
    2. I like Bananas and  Grapes
    3. I like Bananas, Grapes and  Pineapples
    4. I like Bananas, Grapes, Pineapples, Peaches and  Apricots
Nov 27 '13 #6
zmbd
5,501 Expert Mod 4TB
ADezii,
I had thought about the spilit function; however, it just seemd to involve more steps; however lines 14,15 are cool.
Nov 27 '13 #7
Thanks ADezii
Its really cool and working fine...
Thanks once again
Nov 27 '13 #8
I have made only one change to function suggested by ADezii, that I have removed after 'and' in line 12 and 15 to make only one space on both sides of and... Rest its wonderful.
Nov 27 '13 #9
NeoPa
32,556 Expert Mod 16PB
Am I missing something? I don't see that Split() (A wonderful function I use a great deal.) adds anything at all to this process. It doesn't help find the correct comma and only adds code which has a nett value of getting back to where you started from.

Of course, I'm happy (If, I suspect, a little embarrassed) to learn I've missed something obvious (or otherwise) here.

PS. Yousaf, well spotted.
I have to say, that's a very rare miss from ADezii. As you can see, he always tests his posted code. Even for very small bits like this.

I may sometimes (rarely) question his logic, but never his approach ;-)
Nov 28 '13 #10
Thanx ADezii. Its help me too.
Nov 29 '13 #11
ADezii
8,834 Expert 8TB
You are quite welcome.
Nov 29 '13 #12
NeoPa
32,556 Expert Mod 16PB
To illustrate how straightforward the function could be :
Expand|Select|Wrap|Line Numbers
  1. Private Function FixAnd(strIn As String) As String
  2.     Dim lngX As Long
  3.  
  4.     lngX = InStrRev(StringCheck:=strIn, StringMatch:=",")
  5.     FixAnd = IIf(lngX > 0, Left(strIn, lngX - 1) & " and ", "") _
  6.            & Mid(strIn, lngX + 1)
  7. End Function
As I say, there is no need to complicate it further.

For the Oxford Comma version it is simply required to change the literal string " and ", in line #5, to ", and ".
Nov 29 '13 #13
zmbd
5,501 Expert Mod 4TB
( BIG SMILE ) You Brits messing up the English language ( BIG SMILE )

Be nice if the world would agree on one standard (^-^).
Here in the US, for all my short life of some 4+decades the Oxford Comma was taught as the standard. Indeed, my oldest is being taught that way now... and very naively, I thought that was the standard!

Not only do I get to learn something new in programming, I get to learn something about the rest of the world too.

IT's Great!

BOL
-z
Nov 29 '13 #14

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: jcabc | last post by:
I have a text string which has multiple values seperated by commas. My goal is to find the postion of the 4th comma and then read the text after that comma until the next comma using VBA. Ex. ...
19
by: Paul | last post by:
hi, there, for example, char *mystr="##this is##a examp#le"; I want to replace all the "##" in mystr with "****". How can I do this? I checked all the string functions in C, but did not...
2
by: ad | last post by:
I have a string variable lik: sList="1.Tiger, 2.Wolf, 3.Rabbit," I want to trim off the last character "," Have there pre-define function to do that?
25
by: electrixnow | last post by:
in MS VC++ Express I need to know how to get from one comma delimited text string to many strings. from this: main_string = "onE,Two,Three , fouR,five, six " to these: string1 =...
10
by: vabby | last post by:
Hey guys. I have a problem with my code, I can replace comma for a dot here. "var tvn = parseFloat(document.getElementById('ctl00_ContentPlaceHolder1_txtMillilTVNHraefni').value.replace(/,/g,...
3
by: thanawala27 | last post by:
hi I dont know how to seperate a string containing commas. suppose i have a string $text = "this, is, fine"; i want to seperate the above string into this is fine
13
by: SuvarnaChaudhari | last post by:
Hi,I am new to .net. As per ur guidance I tried myString = myString.SubString(0,myString.Length-1); I also used str.lastindexof n str.remove,but by using this I m gettin string as ' (B193 '' H13 ''...
3
by: Donkeyoz | last post by:
Hi all, Trying to do something fairly basic but am getting caught up on it. I am trying to extract text from a .txt file into an array line by line and then dissect that line into various parts,...
4
by: dmitrey | last post by:
hi all, howto split string with both comma and semicolon delimiters? i.e. (for example) get from string "a,b;c" I have tried s.split(',;') but it don't work Thx, D.
3
by: shapper | last post by:
Hello, I need to replace the last comma in a string by " and ". How can I do this? Thanks, Miguel
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.