View Full Version : Substring
youjie
Nov 7th 2006, 11:32 pm
May I know how to get a subtring from a variable?
For example i have the variable
<cfset var = 1234>
how do i get the first 2 letters or 2 last 2 letters. Thanks in advance
seamus.hogan
Nov 10th 2006, 8:44 am
Hi,
To output the first 2
<cfset number1 = 1284>
<cfset val2 = Mid(number1, 1, 2)>
<cfoutput>#val2#</cfoutput>
To output the last 2
<cfset number1 = 1284>
<cfset val2 = Mid(number1, 3, 2)>
<cfoutput>#val2#</cfoutput>
The Mid statement breaks down like this
Mid(a, b, c)
a= string being analysed
b= start positon
c = end position
hope this helps
datropics
Nov 11th 2006, 11:04 am
Seamus - that's pretty cool,
here's an addition for any length string:
<cfset FirstHalfBigger = 0>
<cfset Number = 1234567>
<cfset NumLen = Len(Number)>
<cfset NumHalf = Int(NumLen/2)>
<cfset CompleteHalf = Round(NumLen/2)>
<cfif NumHalf GT 0>
<cfif NumHalf eq CompleteHalf>
<cfset FirstNum = Mid(Number,1,NumHalf)>
<cfset SecondNum = Mid(Number,NumHalf+1,NumHalf)>
<cfelseif FirstHalfBigger eq 1>
<cfset FirstNum = Mid(Number,1,CompleteHalf)>
<cfset SecondNum = Mid(Number,Round(NumLen/2)+1,NumHalf)>
<cfelse>
<cfset FirstNum = Mid(Number,1,CompleteHalf)>
<cfset SecondNum = Mid(Number,NumHalf+1,CompleteHalf)>
</cfif>
<cfoutput>
Original Number: #Number#<br>
1st Half: #FirstNum#<br>
2nd Half: #SecondNum#<br>
</cfoutput>
<cfelse>
Sorry no halves...
</cfif>
Ok if you have the numbers 1234:
FirstNum = 12
SecondNum = 34
If you have the numbers 12345 and FirstHalfBigger is 1 then
FirstNum = 123
SecondNum = 45
If you have the numbers 12345 and FirstHalfBigger is 0 then
FirstNum = 123
SecondNum = 345
I am not sure what your implementation would be so decided to build for both conditions
This should work for any length string, I also put a condition if it turns out that you don't have any halves. Ofcourse you can change this logic if you want - I did this in 5 mins so it may be a little flawed....
daTropics
vBulletin® v3.8.4, Copyright ©2000-2009, Jelsoft Enterprises Ltd.