Unwanted new-line when plugging a string variable into a RichTextBox - string

Im generating a string variable from other string variables that themselves are generated in a button press and take their values from textboxes / user input. Simultaneously, the mass string variable is being loaded into a RichTextBox. While I do purposely use one VbLf in my mass string variable, I am encountering an additional point where a new line begins in my string where it is not supposed too. How can I avoid this?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
numb = numbtxt.Text
year = yeartxt.Text
author = authortxt.Text
pages = pagestxt.Text
pgnum = pgnumtxt.Text
item1 = item1txt.Text
item2 = item2txt.Text
format = numb + ") """ + item1 + """" + vbLf + item2 + _
" - " + author + " (" + year + ") " + pages + " " + pgnum
rtf.Text = format
End Sub
I am expecting this:
https://i.imgur.com/5q5MME2.png
but I am getting this:
https://i.imgur.com/dCMAIqA.png
Any help would be very much so appreciated.

Please check your content of cour variable item2 containing the url. I guess, that this variable contains a line break at the end. Try to just print this variable with a leading and trailing char.
If so, you can either replace the new line character in item2 or try to substring the content.

To remove any unwanted characters from the input strings, you can trim them, or do a character replacement. For example, to remove CR/LF from the end of strings (untested, from memory);
numb = numbtxt.Text.TrimEnd( {vbCr, vbLf, vbCrLf, Environment.Newline} )
or to remove all occurrences;
year = yeartxt.Text.Replace(vbCrLf, String.Empty)
or;
year = yeartxt.Text.Replace(vbCr, String.Empty).Replace(vbLf, String.Empty)
etc. YMMV depending on the actual CR/LF character arrangments and language settings!

Related

VB.NET Get Number Position Of Char In String (Index Of)

im having a hard time getting a function working. I need to search message.text for each "," found, for each "," found I need to get the number position of where the "," is located in the string. For example: 23232,111,02020332,12 it would return 6/10/19 where the "," are located (index of). My code finds the first index of the first , but then just repeats 6 6 6 6 over, any help would be appreciated thanks.
Heres my code:
For Each i As Char In message.Text
If message.Text.Contains(",") Then
Dim data As String = message.Text
Dim index As Integer = System.Text.RegularExpressions.Regex.Match(data, ",").Index
commas.AppendText(index & " ")
End If
Next
You can try it this way; instantiate a Regex object and increment each time the position from which you start the matching (this possibility is not available with the static method Match).
Dim reg As New System.Text.RegularExpressions.Regex(",")
Dim Index As Integer = reg.Match(data).Index
Do While Index > 0
commas.AppendText(index & " ")
Index = reg.Match(data, Index + 1).Index
Loop
p.s the returned indices are zero-based.
Just use the Regex.Matches method
Dim message As String = "23232,111,02020332,12"
Dim result As String = ""
For Each m As Match In Regex.Matches(message, ",")
result &= m.Index + 1 & " "
Next
I should also add that indexes are 0 based (which is why +1 is added to m.Index). If you later need these values to point to the position of a particular comma, you may be off by 1 and could potentially try to access an index larger than the actual string.

How to trim spaces

I have text in Excel like this:
120
124569 abasd 12345
There are sapces both to the left and to the right side.
I copy this from Excel and paste as text. When I check this, it shows like this when I click on button.
Code:
abArray= abArray & "," & gridview1.Rows(i).Cells(2).Text
For k = 3 To 17
bArray= abArray& "," & Val(gridview1.Rows(i).Cells(k).Text)
Next
In abArray this shows as:
0, abasd ,12345,0,0,0,0,0
I want to remove/trim spaces both from left and right.
I have tried abArray.Trim() but this still show spaces.
If you want to remove all the spaces out of the end result consider String.Replace:
Returns a new string in which all occurrences of a specified Unicode character or String in the current string are replaced with another specified Unicode character or String.
Example use:
Dim s As String = "0, abasd ,12345,0,0,0,0,0"
s = s.Replace(" ", "")
This would output:
0,abasd,12345,0,0,0,0,0
It may also be worth using a StringBuilder to join all your values together as this is good practice when looping as you are. At this point you could use String.Trim. This would preserve any spaces that are within your value. In order words it would only remove the spaces from the beginning and the end of the value.
Example use:
Dim sb As New StringBuilder
For k = 0 To 17
sb.Append(String.Format("{0},", gridview1.Rows(i).Cells(k).Text.Trim()))
Next
Dim endResult As String = sb.ToString().TrimEnd(","c)
endResult would output:
0,abasd,12345,0,0,0,0,0
You will have to import System.Text in order to make use of the StringBuilder class.
Use the VB.NET Trim function to remove leading and trailing spaces, change this one line of code:
abArray= abArray& "," & Val(Trim(gridview1.Rows(i).Cells(k).Text))
abArray.Trim() does not work because you did not give the Trim function anything to trim.
Try it like this
abArray = abArray & "," & gridview1.Rows(i).Cells(2).Text.Trim
For k = 3 To 17
abArray= abArray& "," & Val(gridview1.Rows(i).Cells(k).Text.Trim)
Next

MS Access: How do I remove the 13 leading spaces of this field?

I have a table where one of the fields has 13 leading spaces (no visible characters in them). I tried TRIM() and REPLACE([Field1], " ", "") but neither one worked. Could anyone venture a guess as to what's going on and how to fix this?
This is not an answer but it will allow you to see what the chr value is for the string. Just call it like MsgBox WhatAreTheAscValues([Field1]) and you will see what value the characters that make up the string and allow you to adjust your code accordingly.
Function WhatAreTheAscValues(str As String)
Dim i As Integer
Dim answer As String
answer = "The Chr(x) values in this string are listed below" & vbCrLf
For i = 1 To Len(str)
answer = answer + CStr(Asc(Mid(str, i, 1))) & ", "
Next i
WhatAreTheAscValues = Left(answer, Len(answer) - 2)
End Function

VBA Trim leaving leading white space

I'm trying to compare strings in a macro and the data isn't always entered consistently. The difference comes down to the amount of leading white space (ie " test" vs. "test" vs. " test")
For my macro the three strings in the example should be equivalent. However I can't use Replace, as any spaces in the middle of the string (ex. "test one two three") should be retained. I had thought that was what Trim was supposed to do (as well as removing all trailing spaces). But when I use Trim on the strings, I don't see a difference, and I'm definitely left with white space at the front of the string.
So A) What does Trim really do in VBA? B) Is there a built in function for what I'm trying to do, or will I just need to write a function?
Thanks!
So as Gary's Student aluded to, the character wasn't 32. It was in fact 160. Now me being the simple man I am, white space is white space. So in line with that view I created the following function that will remove ALL Unicode characters that don't actual display to the human eye (i.e. non-special character, non-alphanumeric). That function is below:
Function TrueTrim(v As String) As String
Dim out As String
Dim bad As String
bad = "||127||129||141||143||144||160||173||" 'Characters that don't output something
'the human eye can see based on http://www.gtwiki.org/mwiki/?title=VB_Chr_Values
out = v
'Chop off the first character so long as it's white space
If v <> "" Then
Do While AscW(Left(out, 1)) < 33 Or InStr(1, bad, "||" & AscW(Left(out, 1)) & "||") <> 0 'Left(out, 1) = " " Or Left(out, 1) = Chr(9) Or Left(out, 1) = Chr(160)
out = Right(out, Len(out) - 1)
Loop
'Chop off the last character so long as it's white space
Do While AscW(Right(out, 1)) < 33 Or InStr(1, bad, "||" & AscW(Right(out, 1)) & "||") <> 0 'Right(out, 1) = " " Or Right(out, 1) = Chr(9) Or Right(out, 1) = Chr(160)
out = Left(out, Len(out) - 1)
Loop
End If 'else out = "" and there's no processing to be done
'Capture result for return
TrueTrim = out
End Function
TRIM() will remove all leading spaces
Sub demo()
Dim s As String
s = " test "
s2 = Trim(s)
msg = ""
For i = 1 To Len(s2)
msg = msg & i & vbTab & Mid(s2, i, 1) & vbCrLf
Next i
MsgBox msg
End Sub
It is possible your data has characters that are not visible, but are not spaces either.
Without seeing your code it is hard to know, but you could also use the Application.WorksheetFunction.Clean() method in conjunction with the Trim() method which removes non-printable characters.
MSDN Reference page for WorksheetFunction.Clean()
Why don't you try using the Instr function instead? Something like this
Function Comp2Strings(str1 As String, str2 As String) As Boolean
If InStr(str1, str2) <> 0 Or InStr(str2, str1) <> 0 Then
Comp2Strings = True
Else
Comp2Strings = False
End If
End Function
Basically you are checking if string1 contains string2 or string2 contains string1. This will always work, and you dont have to trim the data.
VBA's Trim function is limited to dealing with spaces. It will remove spaces at the start and end of your string.
In order to deal with things like newlines and tabs, I've always imported the Microsoft VBScript RegEx library and used it to replace whitespace characters.
In your VBA window, go to Tools, References, the find Microsoft VBScript Regular Expressions 5.5. Check it and hit OK.
Then you can create a fairly simple function to trim all white space, not just spaces.
Private Function TrimEx(stringToClean As String)
Dim re As New RegExp
' Matches any whitespace at start of string
re.Pattern = "^\s*"
stringToClean = re.Replace(stringToClean, "")
' Matches any whitespace at end of string
re.Pattern = "\s*$"
stringToClean = re.Replace(stringToClean, "")
TrimEx = stringToClean
End Function
Non-printables divide different lines of a Web page. I replaced them with X, Y and Z respectively.
Debug.Print Trim(Mid("X test ", 2)) ' first place counts as 2 in VBA
Debug.Print Trim(Mid("XY test ", 3)) ' second place counts as 3 in VBA
Debug.Print Trim(Mid("X Y Z test ", 2)) ' more rounds needed :)
Programmers prefer large text as may neatly be chopped with built in tools (inSTR, Mid, Left, and others). Use of text from several children (i.e taking .textContent versus .innerText) may result several non-printables to cope with, yet DOM and REGEX are not for beginners. Addressing sub-elements for inner text precisely (child elements one-by-one !) may help evading non-printable characters.

Insert a character into a string at a specified index

So I have an array of indexes of characters in a string that I wish to insert a character before, how do i easily insert a character before each index? So for example:
"The big brown fox ... "
the positions
array = 4,9
the character to insert ','
the result: "The, big, brown fox ..."
Is there a method that provides such an easy utility?
String.insert(originalStr, index, stringToInsert) for example???
Update
The example I provided is just an example implementation. I also may want to do the following:
orginalText = "some text with characters like ; : } <"
in which I may want to insert "\" with the result being:
result = "some text with characters like \; : } \<"
This is hacky and a bit rushed but try this:
Dim sString: sString = "the something something"
Dim position: position = 1
Dim character: character = "F"
if position = 0 then
sString = character + Left(Mid(sString, 1), Len(sString) + 1)
else
sString = Left(sString, position) + character + Left(Mid(sString, position), Len(sString) - position + 1)
end if
Assuming that the indexes are sorted, loop backwards and insert each character.
For lngPos = UBound(alngPositions) to 0 step -1
strText = Left(strText, alngPositions(lngPos) - 1) + "," + Mid(strText, alngPositions(lngPos))
Next
Note that with your example data it will of course produce the string "The, big ,brown fox ... ". The indexes are not pre-added to match the position in the resulting string, are they?
Edit:
An alternative that would be faster for large strings, is to split up the string at the index positions into an array, then join the strings with commas in between:
Dim astrSubstrings(UBound(alngPositions) + 1)
lngLeft = 1
For lngPos = 0 to UBound(alngPositions)
astrSubstrings(lngPos) = Mid(strText, lngLeft, alngPositions(lngPos) - lngLeft)
lngLeft = alngPositions(lngPos)
Next
astrSubstrings(UBound(alngPositions) + 1) = Mid(strText, lngLeft)
strText = Join(astrSubstrings, ",")
I'm not a classic ASP user but you can use substring to get the part of the string up to the index where you have to insert the character, substring the other part of the string and take these two parts and build a new string doing part1 & "," & part2.
Hope it helps.
You should be able to use the split function based on the space between the words - this will return an array of words. You then put a comma after each item in the array and you can get to the requried string that you are looking for. Example here http://www.w3schools.com/VBscript/func_split.asp
It's been a while, but Mid(str, start, [end]) would be the way to go.

Resources