I'm trying to pad a string with 0's to the left.The length of the output string should be 7.
Here's my code :
inputstr = "38"
in = string(7 - Len(inputStr),0) & inputStr
msgbox in
I'm getting error Expected Statement
Please help me
Thank You
The following code will run 5% faster:
inputStr = "38"
result = Right("0000000" & inputStr, 7)
msgbox result
This function will left-pad an input value to the given number of characters using the given padding character without truncating the input value:
Function LPad(s, l, c)
Dim n : n = 0
If l > Len(s) Then n = l - Len(s)
LPad = String(n, c) & s
End Function
Output:
>>> WScript.Echo LPad(12345, 7, "0")
0012345
>>> WScript.Echo LPad(12345, 3, "0")
12345
in is a reserved word so can't be used as a variable name and you must pass a string "0" not an integer 0, so:
inputStr = "38"
result = string(7 - Len(inputStr), "0") & inputStr
msgbox result
Function:
Private Function LPad (str, pad, length)
LPad = String(length - Len(str), pad) & str
End Function
Use:
LPad(12345, "0", 7)
Related
I Have a column which contains multiple unique and duplicate values and I'm looking to extract only the non repeating values. How do i go about it?
Example:
A2: 28; 33; 34; 37; 44
A3: 28; 34; 37
I'm trying to get:
A4: 33; 44
example
I've tried finding an answer but couldn't find a solution for this exact problem.
=LET(a,TEXTJOIN(";",,B2:B4),UNIQUE(--TEXTSPLIT(a,";"),TRUE,TRUE))
I don´t see a way of doing this using only formulas. The best approach would be to save those values as a .csv file, and importing that csv file into Excel. Then, using Power Query, you would do the necessary transformations in order to get the desired result.
Here is a step by step solution:
Get your data into a .csv file
Import the csv file by going into Data > From Text/CSV,= and selecting the file. Then, select the delimiter "Semicolon" and click "Transform Data" to open Power Query:
With Power Query open, select all columns by pressing Ctrl + A, and then go to the "Transform" tab and click "Unpivot Columns". You should have something like this:
Delete the "Attribute" column
Remove duplicates from "Value" column
Click "Close & Load" in the Home tab
You then will have the desired result:
I have an answer which ignores any spaces between the values and formats the result by putting only one space between the values. Call the function with two parameters, the values of the two cells to be merged:
Public Function Uniques(stra As String, strb As String) As String
'Uniques("11; 12; 13; 14; 15", " 11;11; 14; 15; 88; 16 ") ==> "12; 13; 88; 16"
Dim ar() As String, delim As String, ss As String, s As String, alen As Integer
Dim z As Integer, p As Integer, c As Integer
delim = ";"
s = Replace(stra & delim & strb, " ", "")
ar = Split(s, delim)
s = delim & s & delim
alen = UBound(ar)
For c = 0 To alen
If ar(c) <> "" Then
ss = delim & ar(c) & delim
p = InStr(1, s, ss)
If (p > 0) Then
p = InStr(p + 1, s, ss)
If p > 0 Then
s = Replace(s, delim & ar(c), "")
For z = c + 1 To alen
If ar(z) = ar(c) Then ar(z) = ""
Next
End If
End If
End If
Next
If (s = delim) Then
Uniques = ""
Else
s = Mid(s, 2, Len(s) - 2)
s = Replace(s, delim, delim & " ")
Uniques = s
End If
End Function
if the two cells have the same value returns empty string ("")
Use Reduce, Textsplit and Hstack to split each row and add it to a single-row array, then use Reduce again to check the number of times each element of the array occurs, and concatenate it to the output if it only occurs once.
=LET(
data, DROP(
TOCOL(A:A, 1),
1
),
row, DROP(
REDUCE(
"",
data,
LAMBDA(a, c,
HSTACK(
a,
TEXTSPLIT(
c,
"; "
)
)
)
),
,
1
),
MID(
REDUCE(
"",
row,
LAMBDA(a, c,
IF(
SUM(
N(
c =
row
)
) = 1,
a & "; " &
c,
a
)
)
),
3,
99
)
)
I am trying to create an internal function in my FreeBASIC program where i want to check for the word "echo" in the string variable "line0" and if "echo" is part of the string, i want it to echo the input (except "echo")
BASIC's Instr function can search through a string and find out if it contains a certain substring. It can do so starting at the first position of the string or any other position if we mention the value in the parameter list. The result that Instr returns is the character position of the find or else zero to denote that the substring was not found.
It's the optional mentioning of the start position that makes all the difference in writing an algorithm that has to find all occurences of a certain substring.
Once Start = 1 Position = Instr(Start, MyString, MySubString) has found the first substring, we can move the start position to just past the find and start over again. We keep doing so until the Instr function returns zero which tells us there are no more occurences of the substring.
Echo asked: What is this echo that echoes in my ear?
^ ^ ^ ^ ^ ^ ^
1 | | | | | |
+4 5 | | | | |
26 | | | |
+4 30 | | |
36 | |
+4 40 |
0 "Not found"
A function that prints its result directly
This SkipText function expects from 1 to 3 parameters. The second and third parameters are optional because of the mention of a default value in the parameter list.
param1 is the string to search (in)
param2 is the string to search for
param3 can limit the number of removals
Declare Function SkipText (a As String, b As String = "", c As Integer = 1) As Integer
Dim As String s
s = "Echo asked: What is this echo that echoes in my ear?"
Print "The function outputs directly"
Print " Unmodified: ";
SkipText(s)
Print " Modified*1: ";
SkipText(s, "echo", 1)
Print " Modified*2: ";
SkipText(s, "echo", 2)
Print " Modified*3: ";
SkipText(s, "echo", 3)
GetKey ' So you can inspect the output
Function SkipText (a As String, b As String, c As Integer) As Integer
Dim As Integer h, i, j, k
h = IIf(c < 1, 1, c) ' Guard against bogus input
i = 1
j = 1 + Len(a) - Len(b)
Do While i <= j
k = InStr(i, a, b) ' Case-sensitive
If k = 0 Then Exit Do
Print Mid(a, i, k-i);
i = k + Len(b)
h -= 1
If h = 0 Then Exit Do
Loop
Print Mid(a, i)
Return 0
End Function
A function that returns a string that the caller can then print
Next SkipText function expects from 1 to 3 parameters. The second and third parameters are optional because of the mention of a default value in the parameter list.
param1 is the string to search (in)
param2 is the string to search for
param3 can limit the number of removals
If you tried the above code snippet, you will have seen that the first "Echo", the one that starts with a capital, was not removed. This happens because FreeBasic's Instr always works 'case-sensitive'. The simple solution to remove in a 'case-insensitive' way is to use the UCase function like in:
Position = Instr(Start, UCase(MyString), UCase(MySubString))
Declare Function SkipText (a As String, b As String = "", c As Integer = 1) As String
Dim As String s
s = "Echo asked: What is this echo that echoes in my ear?"
Print "The function returns a (reduced) string"
Print " Unmodified: "; SkipText(s)
Print " Modified*1: "; SkipText(s, "echo", 1)
Print " Modified*2: "; SkipText(s, "echo", 2)
Print " Modified*3: "; SkipText(s, "echo", 3)
GetKey ' So you can inspect the output
Function SkipText (a As String, b As String, c As Integer) As String
Dim As String t = ""
Dim As Integer h, i, j, k
h = IIf(c < 1, 1, c) ' Guard against bogus input
i = 1
j = 1 + Len(a) - Len(b)
Do While i <= j
k = InStr(i, UCase(a), UCase(b)) ' Case-insensitive
If k = 0 Then Exit Do
t = t + Mid(a, i, k-i)
i = k + Len(b)
h -= 1
If h = 0 Then Exit Do
Loop
Return t + Mid(a, i)
End Function
() Because these are tiny code snippets, I wasted no time choosing sensible identifiers. In longer programs you should always pick meaningful names for any identifiers.
() FreeBasic comes with a nice, comprehensive manual. If anything isn't clear, first consult the manual, then maybe ask a question on this forum.
did you do any kind of research? Sorry, but I assume you did not.
The answer is, there is already a function for this task builtin in Basic language.
The function you are searching for is "INSTR". Please read the available documentation for FreeBasic. If you then decide to try to write your own INSTR function (if you need a feature which is not provided by the builtin function), try to do your coding, and if you stuck, we´ll try to help.
Your described task will therefore include the following functions:
INSTR ' check if the string is here
LEN ' to know the length of your search string
MID ' to create the 'reduced' output (maybe you will to have it used twice)
How do I make a specific letter of a string uppercase, and not changing any of the other letters?
My example:
"this works" -> "this woRks" //Change made to letter 7
"this works" -> "this wOrks" //Change made to letter 6
"this works" -> "This works" //Change made to letter 1
My system uses characters with a UTF-8 encoding, so it needs to support uppercase for UTF-8 characters and not just ascii.
Unoptimized one-liner :)
julia> s = "this is a lowercase string"
"this is a lowercase string"
julia> String([i == 4 ? uppercase(c) : c for (i, c) in enumerate(s)])
"thiS is a lowercase string"
This is how can you do it with slicing a string:
In Julia 0.6
function uppercasen(s::AbstractString, i::Int)
0 < i <= length(s) || error("index $i out of range")
pos = chr2ind(s, i)
string(s[1:prevind(s, pos)], uppercase(s[pos]), s[nextind(s, pos):end])
end
for i in 1:3
println(uppercasen("kół", i))
end
In Julia 0.7 (here I use SubString as it will be a bit faster than using String - similar thing can be done in Julia 0.6)
function uppercasen(s::AbstractString, i::Int)
0 < i <= length(s) || error("index $i out of range")
pos = nextind(s, 0, i)
string(SubString(s, 1, prevind(s, pos)), uppercase(s[pos]), SubString(s, nextind(s, pos)))
end
for i in 1:3
println(uppercasen("kół", i))
end
However, the code below should work under both versions of Julia (unfortunately it is slower):
function uppercasen(s::AbstractString, i::Int)
0 < i <= length(s) || error("index $i out of range")
io = IOBuffer()
for (j, c) in enumerate(s)
write(io, i == j ? uppercase(c) : c)
end
String(take!(io))
end
Here's another snippet if you're working with simple ASCII strings:
toupper(x, i) = x[1:i-1] * uppercase(x[i:i]) * x[i+1:end]
julia> toupper("this works", 1)
"This works"
julia> toupper("this works", 4)
"thiS works"
julia> toupper("this works", 7)
"this wOrks"
A slight advantage of this approach is that it can be trivially adapted as
`toupper(x, i, j) = x[1:i-1] * uppercase(x[i:j]) * x[j+1:end]`
to convert to uppercase a range within the string as opposed to a single letter.
option explicit
dim r, res, num
num= cint(inputbox("Enter the number"))
do while(num > 0)
r= num mod 10
num= num\10
res= res & r
loop
msgbox res
Well this is the code, now my question is this works perfectly fine for input 1234, well if the input is 0123 it just prints 321 which is wrong.It needs to print 3210.
I am unable to figure out, tried a lot but in vain, any help would be appreciated
Thanks and Regards
You must decide whether you want to reverse strings or numbers (accidentially represented as decimals). If you want to reverse strings, you should
not convert the (string) input to a number/integer
use string ops: Mid() for reading, concatenation & for building
Added: In (demo/not production) code:
Option Explicit
Function rev(s)
Dim p
For p = Len(s) To 1 Step -1
rev = rev & Mid(s, p, 1)
Next
End Function
Dim s
For Each s In Array("1234", "0123")
WScript.Echo s, rev(s)
Next
output:
1234 4321
0123 3210
str = Inputbox("Enter the number")
rev=""
Set regx = New RegExp
regx.Global = True
regx.IgnoreCase = True
regx.Pattern = ".{1}"
Set colchars= regx.Execute(str)
For i = 0 To colchars.Count-1
rev= colchars.Item(i)&rev
Next
MsgBox rev
String reverse program without using Reverse String function & Mid function.
str=inputbox("Enter the string: ")
str1=len(str)
a=Left(str,1)
for i=1 to str1
str2=Left(str,i)
if len(str2)>1 then
str3=Right(str2,1)&temp
temp=str3
end if
next
msgbox temp&a
Try this:
Dim num, rev
num = inputbox("Enter a number")
If Len(num)=4 Then
rev = rev*10 + num mod 10
num = num/10
num = left(num,3)
rev = rev*10 + num mod 10
num = num/10
num = left(num,2)
rev = rev*10 + num mod 10
num = num/10
num = left(num,1)
rev = rev*10 + num mod 10
msgbox "Reverse Order of the number is "&rev
Else
msgbox "Number, you entered is not a 4 digit number"
End If
I am trying to find a way to take a string of HEX values and convert them to BIN. I need to convert 1 HEX character at a time:
For example: HEX = 0CEC
BIN = 0000 1100 1110 1100
I need to do this in Excel. Any help would be great.
Thanks,
Larry
In a module:
Public Function HEX2BIN(strHex As String) As String
Dim c As Long, i As Long, b As String * 4, j As Long
For c = 1 To Len(strHex)
b = "0000"
j = 0
i = Val("&H" & Mid$(strHex, c, 1))
While i > 0
Mid$(b, 4 - j, 1) = i Mod 2
i = i \ 2
j = j + 1
Wend
HEX2BIN = HEX2BIN & b & " "
Next
HEX2BIN = RTrim$(HEX2BIN)
End Function
For:
=HEX2BIN("0CEC")
0000 1100 1110 1100
Yes, I had to do this recently. I'm late to the game, but other people will have to do this from time to time, so I'll leave the code where everyone can find it:
Option Explicit
Public Function HexToBinary(strHex As String, Optional PadLeftZeroes As Long = 5, Optional Prefix As String = "oX") As String
Application.Volatile False
' Convert a hexadecimal string into a binary
' As this is for Excel, the binary is returned as string: there's a risk that it will be treated as a number and reformatted
' Code by Nigel Heffernan, June 2013. Http://Excellerando.Blogspot.co.uk THIS CODE IS IN THE PUBLIC DOMAIN
' Sample Usage:
'
' =HexToBinary("8E")
' oX0010001110
'
' =HexToBinary("7")
' oX001111
'
' =HexToBinary("&HD")
' oX01101
Dim lngHex As Long
Dim lngExp As Long
Dim lngPad As Long
Dim strOut As String
Dim strRev As String
If Left(strHex, 2) = "&H" Then
lngHex = CLng(strHex)
Else
lngHex = CLng("&H" & strHex)
End If
lngExp = 1
Do Until lngExp > lngHex
' loop, bitwise comparisons with successive powers of 2
' Where bitwise comparison is true, append "1", otherwise append 0
strRev = strRev & CStr(CBool(lngHex And lngExp) * -1)
lngExp = lngExp * 2
Loop
' As we've done this in ascending powers of 2, the results are in reverse order:
If strRev = "" Then
HexToBinary = "0"
Else
HexToBinary = VBA.Strings.StrReverse(strRev)
End If
' The result is padded by leading zeroes: this is the expected formatting when displaying binary data
If PadLeftZeroes > 0 Then
lngPad = PadLeftZeroes * ((Len(HexToBinary) \ PadLeftZeroes) + 1)
HexToBinary = Right(String(lngPad, "0") & HexToBinary, lngPad)
End If
HexToBinary = Prefix & HexToBinary
End Function
You can use HEX2BIN(number, [places]).
The HEX2BIN function syntax has the following arguments:
Number Required. The hexadecimal number you want to convert. Number cannot contain more than 10 characters. The most significant bit of number is the sign bit (40th bit from the right). The remaining 9 bits are magnitude bits. Negative numbers are represented using two's-complement notation.
Places Optional. The number of characters to use. If places is omitted, HEX2BIN uses the minimum number of characters necessary. Places is useful for padding the return value with leading 0s (zeros).
I would use a simple formula as follows:
=HEX2BIN(MID(S23,1,2))&HEX2BIN(MID(S23,3,2))&HEX2BIN(MID(S23,5,2))&HEX2BIN(MID(S23,7,2)&HEX2BIN(MID(S23,9,2)&HEX2BIN(MID(S23,11,2)&HEX2BIN(MID(S23,13,2))
cell S23 = BFBEB991, Result = 10111111101111101011100110010001
This would allow it to be as long you need. Just add as many repetitions as you need incrementing the start position by 2 (eg 1, 3, 5, 7, 9, 11, 13, 15, ....). Note that the missing characters will be ignored.
For me, it gives this (sorry, in VBA, but has the advantage of not asking you the length of your string to convert). Be careful, I put a comment in the lower part for which you can add a space between each section of 4 bits. Some don't want the space and some will need it:
Length = Len(string_to_analyse)
For i = 1 To Length
Value_test_hexa = Left(Right(string_to_analyse, Length - (i - 1)), 1)
'get the asci value of each hexa character (actually can work as a decimal to binary as well)
Value_test = Asc(Value_test_hexa)
If Value_test > 47 And Value_test < 58 Then
Value_test = Value_test - 48
End If
' Convert A to F letters to numbers from 10 to 15
If Value_test > 64 And Value_test < 71 Then
Value_test = Value_test - 55
End If
'identify the values of the 4 bits for each character (need to round down)
a = WorksheetFunction.RoundDown(Value_test / 8, 0)
b = WorksheetFunction.RoundDown((Value_test - a * 8) / 4, 0)
c = WorksheetFunction.RoundDown((Value_test - a * 8 - b * 4) / 2, 0)
d = (Value_test - a * 8 - b * 4 - c * 2)
Value_converted = Value_converted & a & b & c & d ' can eventually add & " " in order to put a space every 4 bits
Next i
Tested OK so you can go with it.
Just leaving this here for anyone who needs it.
Instead of manually converting from hex to binary, I used Excel's built-in HEX2BIN function.
Function hexToBin(hexStr As String) As String
Dim i As Integer, b As String, binStr As String
For i = 1 To Len(hexStr)
b = Application.hex2bin(Mid(hexStr, i, 1), 4)
binStr = binStr & b
Next i
hexToBin = binStr
End Function