Can I specify the starting and Ending Index in String.Join ?
Just to clarify, say I have array A (dimensioned 0 to 20) and I would like to join elements 4 to 10, can this be done with String.Join?
The way I currently do it is
Dim Str as String
Str = ""
For I = 4 to 10
Str = Str & A(I)
Next
Is there an alternative to this?
Thanks in advance
You can use Linq to extract only the array subset you want and pass it to String.Join in a single line of code.
Dim Str = String.Join("", a.Skip(3).Take(7))
(By the way, this has also the added benefit that if your array doesn't contain 10 elements you don't get an IndexOutOfRange exception)
Related
I have a string that contains numbers
label1.text = 2,8,11,9,1,12
Now when I replace 1 it replaces 11 too and I don't want that to happen
I would like when I remove something it just remove the specific thing
but 1 will also remove 11
I'm using this for a branchaccess for multiple branch the numbers are the ids of the branch
label1.text = 2,8,11,9,1,12
Dim newstring As String
newstring = Label1.Text.Replace("," & "1", "")
Label1.Text = newstring
Can anyone please help me? Thank you
Provided that there are never spaces between your numbers, you could do something like:
label1.text = "2,8,11,9,1,12"
Dim newstring As String
newstring = label1.Text.Replace(",1,", ",")
If newstring.StartsWith("1,") Then
newstring = newstring.Substring(2)
End If
If newstring.EndsWith(",1") Then
newstring = newstring.Substring(0, newstring.Length - 2)
End If
label1.Text = newstring
This does three things:
Replace instances of ,1, with , (removing 1 and one comma from the middle of the text)
Remove 1, from the start of the string (only if it is there)
Remove ,1 from the end of the string (only if it is there)
You could also use a Regular Expression to achieve the same result, which may be cleaner or more efficient.
Perhaps a better way would be store the branch IDs separately and join them together only when you want to show them in the label.
For example,
Dim branchIds As New List(Of Integer) From {2, 8, 11, 9, 1, 12}
branchIds.Remove(1)
Label1.Text = String.Join(",", branchIds)
results in Label1 showing 2,8,11,9,12.
That way, you could change the "," to, say, ", " to improve readabilty, and it would make no difference to how the branch IDs are processed. It is a good idea to separate the data from the display of the data.
I'm trying to find a way to trim strings before a substring, in a way that only the left of the string is returned.
Before:
[REMOVE] = 1 (Line0)
G77 H9002 (Line1)
[ZAXIS] = 25 (Line2)
After:
[REMOVE] = 1
G77 H9002
[ZAXIS] = 25
I want to trim the strings before the "(line" substring (removing all characters remaining on the right as well).
In VBA this was easily achievable but in VB .Net its not so straightforward.
Could you please direct me to a possible solution?
Thanks
Dim strs = File.ReadLines("c:\\SomeFile.txt") 'Read the file
Using sw = File.CreateText("c:\Target") 'File to save to
For Each str In strs
Dim i = str.LastIndexOf("(Line") 'Find the index to cut
Dim newStr = str.Substring(0, i) 'Cut the line at index
sw.WriteLine(newStr) 'Write new string to new file.
Next
End Using
I'm using this query in vb.net
Raw_data = Alltext_line.Substring(Alltext_line.IndexOf("R|1"))
and I want to increase R|1 to R|2, R|3 and so on using for loop.
I tried it many ways but getting error
string to double is invalid
any help will be appreciated
You must first extract the number from the string. If the text part ("R") is always separated from the number part by a "|", you can easily separated the two with Split:
Dim Alltext_line = "R|1"
Dim parts = Alltext_line.Split("|"c)
parts is a string array. If this results in two parts, the string has the expected shape and we can try to convert the second part to a number, increase it and then re-create the string using the increased number
Dim n As Integer
If parts.Length = 2 AndAlso Integer.TryParse(parts(1), n) Then
Alltext_line = parts(0) & "|" & (n + 1)
End If
Note that the c in "|"c denotes a Char constant in VB.
An alternate solution that takes advantage of the String type defined as an Array of Chars.
I'm using string.Concat() to patch together the resulting IEnumerable(Of Char) and CInt() to convert the string to an Integer and sum 1 to its value.
Raw_data = "R|151"
Dim Result As String = Raw_data.Substring(0, 2) & (CInt(String.Concat(Raw_data.Skip(2))) + 1).ToString
This, of course, supposes that the source string is directly convertible to an Integer type.
If a value check is instead required, you can use Integer.TryParse() to perform the validation:
Dim ValuePart As String = Raw_data.Substring(2)
Dim Value As Integer = 0
If Integer.TryParse(ValuePart, Value) Then
Raw_data = Raw_data.Substring(0, 2) & (Value + 1).ToString
End If
If the left part can be variable (in size or content), the answer provided by Olivier Jacot-Descombes is covering this scenario already.
Sub IncrVal()
Dim s = "R|1"
For x% = 1 To 10
s = Regex.Replace(s, "[0-9]+", Function(m) Integer.Parse(m.Value) + 1)
Next
End Sub
I have a script that takes the contents of a cell, and puts the first 2 characters of the cell into a string array. I need to later compare that string array to a string, but I can't seem to get that to work. Here's what I have:
For i = 2 To 600
colStr = Sheets("smartlist").Cells(i, "A").Value
If colStr <> "" Then
ReDim charArray(Len(colStr) - 1)
For j = 1 To Len(colStr)
charArray(j - 1) = Mid$(colStr, j, 1)
Next
strArray = LCase(charArray(0)) & LCase(charArray(1))
If CStr(Join(strArray)) = CStr(Join(pwArray)) Then
Now, I've tried:
If charArray = "ab"
If Join(charArray) = "ab"
If CStr(Join(charArray)) = "ab"
I'm pretty lost at this point. Any suggestions would be welcome!
Edit: added the whole function up until I get the 'Type mismatch'
You could use Join(charArray, "") - without "" it joins the elements with space so the result of your initial try was "a b"
Firstly, you really need to clarify what you're doing. You say that later you need to check what's in the string. If that is the case, then you don't need an array, you simply need another string...
Dim chars As String
chars = Left$(cellToTest, 2)
Later you can test more simply using the InStr function, like so...
Dim loc As Integer
loc = Instr(colStr, chars)
If loc > 0 Then
...
If you want to turn this into a function on your spreadsheet you can use the following in the cells as formulas...
=LEFT(A1, 2)
=SEARCH(A3, A1)
Here's a little screen shot of what I mean...
lets say I have a string that I want to split based on several characters, like ".", "!", and "?". How do I figure out which one of those characters split my string so I can add that same character back on to the end of the split segments in question?
Dim linePunctuation as Integer = 0
Dim myString As String = "some text. with punctuation! in it?"
For i = 1 To Len(myString)
If Mid$(entireFile, i, 1) = "." Then linePunctuation += 1
Next
For i = 1 To Len(myString)
If Mid$(entireFile, i, 1) = "!" Then linePunctuation += 1
Next
For i = 1 To Len(myString)
If Mid$(entireFile, i, 1) = "?" Then linePunctuation += 1
Next
Dim delimiters(3) As Char
delimiters(0) = "."
delimiters(1) = "!"
delimiters(2) = "?"
currentLineSplit = myString.Split(delimiters)
Dim sentenceArray(linePunctuation) As String
Dim count As Integer = 0
While linePunctuation > 0
sentenceArray(count) = currentLineSplit(count)'Here I want to add what ever delimiter was used to make the split back onto the string before it is stored in the array.'
count += 1
linePunctuation -= 1
End While
If you add a capturing group to your regex like this:
SplitArray = Regex.Split(myString, "([.?!])")
Then the returned array contains both the text between the punctuation, and separate elements for each punctuation character. The Split() function in .NET includes text matched by capturing groups in the returned array. If your regex has several capturing groups, all their matches are included in the array.
This splits your sample into:
some text
.
with punctuation
!
in it
?
You can then iterate over the array to get your "sentences" and your punctuation.
.Split() does not provide this information.
You will need to use a regular expression to accomplish what you are after, which I infer as the desire to split an English-ish paragraph into sentences by splitting on punctuation.
The simplest implementation would look like this.
var input = "some text. with punctuation! in it?";
string[] sentences = Regex.Split(input, #"\b(?<sentence>.*?[\.!?](?:\s|$))");
foreach (string sentence in sentences)
{
Console.WriteLine(sentence);
}
Results
some text.
with punctuation!
in it?
But you are going to find very quickly that language, as spoken/written by humans, does not follow simple rules most of the time.
Here it is in VB.NET for you:
Dim sentences As String() = Regex.Split(line, "\b(?<sentence>.*?[\.!?](?:\s|$))")
Once you've called Split with all 3 characters, you've tossed that information away. You could do what you're trying to do by splitting yourself or by splitting on one punctuation mark at a time.