Is there a BASIC command to count the number of characters in a string? - basic

I couldn't find any. Is there one? Google didn't help me, because it's case insensitive and thinks I am looking for "basic" commands.

Use LEN(expression), where the expression can be any string or string variable
Example:
X = LEN("Jack Daniels") >>> X contains 12
or
strX = "Jack"
X = LEN(strX) >>> X contains 4

All Basic dialects I know of have a len function that returns the length of a string expression. Examples:
Apple // Integer basic
Visual Basic 6
Visual Basic .NET
http://www.fact-index.com/b/ba/basic_programming_language.html
In Visual Basic .NET you could also use the .Length property of the string, but that property behaves differently for the Nothing value: Len() function vs String.Length property; which to choose?

Use the Len
Dim YourString as String
Dim CharCount as Integer
YourString ="MyString"
CharCount = LEN(YourString)
msgbox "There are " & CharCount & " Characters in mystring"

If you mean that you want to count the number of a specific character in a , you can do something like that :
Dim YourString as String
Dim CharCount as Integer
Dim MyChr as Char
Dim chrl as Char
YourString ="MyString"
MyChr ="A"
CharCount = 0
For i = 1 To Len(YourString)
chrl = Mid(YourString, i, 1)
if UCase(chrl) = UCase(MyChr) then
CharCount = CharCount + 1
end if
next i
msgbox "There are " & CharCount & " " & MyChr & " Characters in mystring"

Yes, look at this example:
' Initializes variable.
Dim TestString As String = "Hello World"
' Returns 11.
Dim TestLen As Integer = Len(TestString)
So TestString = Hello World, and the TestLen = 11 because Hello World has 11 characters in it.

conta = strlen(name_of_variable)
strlen gives the number of character of variables given an integer

Related

VBA # trim string to remove characters

i have a file name the i need to remove some characters below is file name and the goal after trim filename.
My Current String = "text_12_12_19.pdl"
New String Goal = "Text.pdl"
You can use Split:
MyStringGoal = Split(MyCurrentString, "_")(0) & "." & Split(MyCurrentString, ".")(1)
Assuming you are looking to obtain all characters preceding the first underscore, I would suggest the following:
Function TrimFilename(fnm As String) As String
Dim i As Long, j As Long
i = InStr(fnm, "_")
j = InStrRev(fnm, ".")
If 0 < i And i < j Then
TrimFilename = Mid(fnm, 1, i - 1) & Mid(fnm, j)
Else
TrimFilename = fnm
End If
End Function
?TrimFilename("text_12_12_19.pdl")
text.pdl
'Another solution (can also use left and right) :
Dim my_current_string As String
Dim New_String_Goal As String
Dim r As String, l As String
my_current_string = "text_12_12_19.pdl"
l = Left(my_current_string, 4)
r = Right(my_current_string, 4)
New_String_Goal = l & r
Debug.Print New_String_Goal

How can I find quoted text in a string?

Example
Say I have a string:
"I say ""Hello world"" and she says ""Excuse me?"""
VBA will interpret this string as:
I say "Hello world" and she says "Excuse me?"
A more complex example:
I have a string:
"I say ""Did you know that she said """"Hi there!"""""""
VBA interprets this string as:
I say "Did you know that she said ""Hi there!"""
If we remove "I say "
"Did you know that she said ""Hi there!"""
we can continue parsing the string in vba:
Did you know that she said "Hi there!"
Problem
Ultimately I want some function, sBasicQuote(quotedStringHierarchy as string), which returns a string containing the next level up in the string hierarchy.
E.G.
dim s as string
s = "I say ""Did you know that she said """"Hi there!"""""""
s = sBasicQuote(s) ' returns 'I say "Did you know that she said ""Hi there!"""'
s = sBasicQuote(s) ' returns 'Did you know that she said "Hi there!"'
s = sBasicQuote(s) ' returns 'Hi there!'
I just can't figure out an algorithm that would work with this... You almost need to replace all double quotes, but when you've replaced the nth double quote you have to skip to the n+1th douple quote?
How does one implement this in VBA?
You could do something like this
Public Sub test()
Dim s As String
s = "I say ""Did you know that she said """"Hi there!"""""""
Debug.Print DoubleQuote(s, 0)
Debug.Print DoubleQuote(s, 1)
Debug.Print DoubleQuote(s, 2)
End Sub
Public Function DoubleQuote(strInput As String, intElement As Integer) As String
Dim a() As String
strInput = Replace(strInput, String(2, Chr(34)), String(1, Chr(34)))
a = Split(strInput, chr(34))
DoubleQuote = a(intElement)
End Function
Another slightly modified version is a little more accurate
`Public Function DoubleQuote(strInput As String, intElement As Integer) As String
Dim a() As String
Dim b() As String
Dim i As Integer
ReDim b(0)
a = Split(strInput, Chr(34))
' ***** See comments re using -1 *******
For i = 0 To UBound(a) - 1
If Len(a(i)) = 0 Then
b(UBound(b)) = Chr(34) & a(i + 1) & Chr(34)
i = i + 1
Else
b(UBound(b)) = a(i)
End If
ReDim Preserve b(UBound(b) + 1)
Next i
DoubleQuote = b(intElement)
End Function`
I think the following will return what you are looking for in your nested quote example. Your first example is not really a situation of nested quotes.
Option Explicit
Sub NestedQuotes()
Const s As String = "I say ""Did you know that she said """"Hi there!"""""""
Dim COL As Collection
Dim Start As Long, Length As Long, sTemp As String, V As Variant
Set COL = New Collection
sTemp = s
COL.Add sTemp
Do Until InStr(sTemp, Chr(34)) = 0
sTemp = COL(COL.Count)
sTemp = Replace(sTemp, String(2, Chr(34)), String(1, Chr(34)))
Start = InStr(sTemp, Chr(34)) + 1
Length = InStrRev(sTemp, Chr(34)) - Start
sTemp = Mid(sTemp, Start, Length)
COL.Add sTemp
Loop
For Each V In COL
Debug.Print V
Next V
End Sub
My Solution
I spent some more time thinking and came up with this solution.
Function sMineDoubleQuoteHierarchy(s As String) As String
'Check the number of quotes in the string are even - sanity check
If (Len(s) - Len(Replace(s, """", ""))) Mod 2 <> 0 Then sMineDoubleQuoteHierarchy = "Error - Odd number of quotes found in sMineDoubleQuoteHierarchy() function": Exit Function
'First thing to do is find the first and last *single* quote in the string
Dim lStart, lEnd, i As Long, fs As String
lStart = InStr(1, s, """")
lEnd = InStrRev(s, """")
'After these have been found we need to remove them.
s = Mid(s, lStart + 1, lEnd - lStart - 1)
'Start at the first character
i = 1
Do While True
'Find where the next double quote is
i = InStr(1, s, """""")
'if no double quote is found then concatenate with fs with the remainder of s
If i = 0 Then Exit Do
'Else add on the string up to the char before the ith quote
fs = fs & Left(s, i - 1)
'Replace the ith double quote with a single quote
s = Left(s, i - 1) & Replace(s, """""", """", i, 1)
'Increment by 1 (ensuring the recently converted double quote is no longer a single quote
i = i + 1
Loop
'Return fs
sMineDoubleQuoteHierarchy = s
End Function
What's going on in this solution?
The first part of the process is removing the first and last single quote from the string and returning the text between them. Then we loop through the string replacing each instance of "" and replacing it with ". Each time we do this we skip to the next character to unsure strings like """" go to "" instead of ".
Does anyone else have a better/more compact solution?
Edit
After all the suggestions in this forum I settled with this. It's got some extra error trapping to find validate nested strings.
Public Function DoubleQuoteExtract(ByVal s As String, Optional ByRef ErrorLevel As Boolean) As String
'This effectively parses the string like BASIC does by removing incidents of "" and replacing them with "
'SANITY CHECK - Check even number of quotes
Dim countQuote As Double
countQuote = Len(s) - Len(Replace(s, """", ""))
'Calculate whether or not quote hierarchy is correct:
'"..." - Is okay - Count Quotes = 2 - Count Quotes / 2 = 1
'""..."" - Is not okay - Count Quotes = 4 - Count Quotes / 2 = 2
'"""...""" - Is okay - Count Quotes = 6 - Count Quotes / 2 = 3
'""""..."""" - Is not okay - Count Quotes = 8 - Count Quotes / 2 = 4
'etc.
'Ultimately: IF CountQuotes/2 = Odd The string hierarchy is setup fine
' IF CountQuotes/2 = Even, The string Hierarchy is setup incorrectly.
Dim X As Double: X = countQuote / 2
Dim ceil As Long: ceil = Int(X) - (X - Int(X) > 0)
If ceil Mod 2 <> 0 Then sDoubleQuoteExtract = "#Error - Incorrect number of double quotes forming an incomplete hierarchy.": GoTo ErrorOccurred
'If an odd number of quotes are found then they cannot be paired correctly, thus throw error
If countQuote Mod 2 <> 0 Then sDoubleQuoteExtract = "#Error - Odd number of quotes found in sMineDoubleQuoteHierarchy() function": GoTo ErrorOccurred
'Find the next incident of single quote. Trim the string to this
s = Mid(s, InStr(1, s, String(1, Chr(34))))
'replace all instances of "" with "
s = Replace(s, String(2, Chr(34)), String(1, Chr(34)))
'Finally trim off the first and last quotes
DoubleQuoteExtract = Mid(s, 2, Len(s) - 2)
ErrorLevel = False
Exit Function
ErrorOccurred:
ErrorLevel = True
End Function

Compare two string values and return the common string

This is what I would like to do in Excel.
A1 = Hello my name is John
B1 = Hello my name is Joe
C1 = Hello my name is
A2 = Where is John going out tomorrow?
B2 = Where is Joe going out tomorrow?
C1 = Where is
As you can see, I want to compare 2 cells and return the common string until there is a difference. (Stop the comparison as soon there is a change)
I have seen something similar here but is it slightly different from my request.
Thanks in advance.
You should search for a more efficient way but here's one in VBA:
Dim stringA As String
Dim stringB As String
Dim finalString As String
Dim currentLetter As Integer
For currentLetter = 0 To Len(stringA)
If Left(stringA, currentLetter) = Left(stringB, currentLetter) Then
finalString = Left(stringA, currentLetter)
Exit For
End If
Next
Replace the string variables by your cells and it's done.
I liked the challenge, so here is a formula solution I came up with:
=LEFT(A1,LOOKUP(2,1/(MID(LEFT(A1,MATCH(FALSE,INDEX(MID(A1,ROW($1:$99),1)=MID(B1,ROW($1:$99),1),),0)-1),ROW($1:$99),1)=" "),ROW($1:$99))-1)
The answer that was here was fine, only one thing was wrong (at least for me). I can't comment so I am pasting the solution here with my fix. "Exit for" was not needed:
Dim stringA As String
Dim stringB As String
Dim finalString As String
Dim currentLetter As Integer
For currentLetter = 0 To Len(stringA)
If Left(stringA, currentLetter) = Left(stringB, currentLetter) Then
finalString = Left(stringA, currentLetter)
End If
Next
Sub CommonText()
'Finds the longest substring that string A and string B have in common.
sA = "Hey, My Name is John"
sB = "My Name is Eric"
Dim iLtrA As Integer
Dim iLtrB As Integer
Dim sThisString As String
Dim sFinalString As String
sFinalString = ""
For iLtrA = 1 To Len(sA)
For iLtrB = 1 To Len(sB)
For n = 1 To Application.Min(Len(sA), Len(sB))
'mid(text,start, length)
If Mid(sA, iLtrA, n) = Mid(sB, iLtrB, n) Then
sThisString = Mid(sA, iLtrA, n)
If Len(sThisString) >= Len(sFinalString) Then
sFinalString = sThisString
End If
End If
Next n
Next iLtrB
Next iLtrA
Debug.Print sFinalString
End Sub

Replace only last occurrence of match in a string in VBA

I have a string like this
"C://Documents/TestUser/WWW/Help/Files/Move_Help.txt"
and have to replace Move_Help.txt with Move_Job.txt
I am using the below code in VBA EXCEL
str = "C://Documents/TestUser/WWW/Help/Files/Move_Help.txt"
rlpStr = Replace(str, 'Help', 'Job')
I am getting
"C://Documents/TestUser/WWW/Job/Files/Move_Job.txt"
Expected
"C://Documents/TestUser/WWW/Help/Files/Move_Job.txt"
Can you please help on this.
FYI : I can't match Move_Help to Move_Job (Move_ is not constant. It can be any string)
There's a one-line solution for this:
rlpStr = StrReverse(Replace(StrReverse(str), StrReverse("Help"), StrReverse("Job"), , 1))
Technically, it's slightly less efficient than combining InStr and Replace but it can be used inside another expression if you need to. Also, I like the one-line solutions so long as they're not incomprehensible.
Would the technique in the code below meet your requirement?
The intial value of Str is:
C://Documents/TestUser/WWW/Help/Files/Move_Help.txt
The final value is:
C://Documents/TestUser/WWW/Help/Files/Move_Job.txt
The code uses InStrRev to locate the last occurrence of ValueCrnt, if any, If ValueCrnt is present, it replaces that final occurrence with ValueNew.
Option Explicit
Sub Demo()
Dim Pos As Long
Dim Str As String
Dim ValueCrnt As String
Dim ValueNew As String
Str = "C://Documents/TestUser/WWW/Help/Files/Move_Help.txt"
ValueCrnt = "Help"
ValueNew = "Job"
Pos = InStrRev(Str, ValueCrnt)
If Pos > 0 Then
Str = Mid(Str, 1, Pos - 1) & Replace(Str, ValueCrnt, ValueNew, Pos)
End If
Debug.Print Str
End Sub
Str = "C://Documents/TestUser/WWW/Help/Files/Move_Help.txt"
ValueCrnt = "Help"
ValueNew = "Job"
Pos = InStrRev(Str, ValueCrnt)
If Pos > 0 Then
Str = Mid(Str, 1, Pos - 1) & Replace(Str, ValueCrnt, ValueNew, Pos)
End If
Wscript.Echo Str

Replace everything except numbers in a string vb6

well i did my research and seen a lot of posts about this but couldnt find a solution in VB6
so how can i do this in VB6?
lets say i got a string like:
" Once upon a time there was a little kid who wonders about going further than 1000 of miles away from home... "
i want to get only numbers "1000" in this string seperated from string and wanna replace the whole string but numbers should stand still.
The simplest way is to walk the string and copy numbers to a new one:
Function GetNumbers(Value As String) As String
Dim Index As Long
Dim Final As String
For Index = 1 To Len(Value)
If Mid(Value, Index, 1) Like "[0-9]" Then
Final = Final & Mid(Value, Index, 1)
End If
Next
GetNumbers = Final
End Function
The result:
?GetNumbers("abc12def345")
12345
This is inefficient with long strings when there are lots of numbers though.
Building on Deanna's answer:
Function GetNumbers(Value As String) As String
Dim Index As Long
Dim Digit As String
Dim Final As String
Dim Count As Long
Count = 1
GetNumbers = Space(Len(Value))
For Index = 1 To Len(Value)
Digit = Mid(Value, Index, 1)
If Digit Like "[0-9]" Then
Mid(GetNumbers, Count, 1) = Digit
Count = Count + 1
End If
Next
GetNumbers = Left(GetNumbers, Count - 1)
End Function
This function should be O(n)
?GetNumbers("abc12def345")
12345
You may use regular expressions:
Dim NumExp As New RegExp
NumExp.Pattern = "\D"
NumExp.Global = True
strOutput = NumExp.Replace(strWhatToReplace, strReplaceWithWhat)
nStr = "abc12def345"
For X = 1 To Len(nStr)
If IsNumeric(Mid(nStr, X, 1)) = True Then
nNum = nNum & Mid(nStr, X, 1)
End If
Next X
MsgBox nNum

Resources