split string without delimiter and stored in an array using vb.net - vb.net

The variable datatype is string .it contain string value like greater than 300 chars. i want to split that string by 150 char and stored in the string array using vb.net
My code:
msg = t1("fld_msg")
msg1 = msg.Length
For i = 0 To msg.Length - 1
strarr = msg.Substring(0, 150)
Next
Error:
value of type string cant be converted into one dimensional array

You need a counter to increment the cells in the array
msg = t1("fld_msg")
msg1 = msg.Length
dim Counter as Integer = 0
For i = 0 To msg.Length - 1 Step 150
strarr(Counter) = msg.Substring(i, 150)
Counter += 1
Next

Substring returns a value of type string.
You are trying to put the results into an array.
Try:-
strarr(0) = msg.Substring(0,150)
strarr(1) = msg.Substring(150)

Required correction in your code is to assign substring value to an index of array "strarr(i)" rather than to an array "strarr". Also taking a substring like (0,XX) is not correct. Every time it will return a substring from index 0, use (i*NumberOfCharactersToInclude,XX) instead. But here 'XX' also matters.
For example,
if string has 311 characters and XX is fixed to 150, it will lead to an error in third substring. So i would suggest you to go with this one: (Assuming Framework is 3.5 or above)
For i As Integer = 0 To len ' len represents possible no. of substrings
strarr(i) = New String(msg.Skip(i * 150).Take(150).ToArray)
Next

Related

How to increase numeric value present in a string

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

Shift letters to the end of a string Visual Basic

I'm trying to shift letters to the end of the word. Like the sample output I have in the image.
Using getchar and remove function, I was able to shift 1 letter.
mychar = GetChar(word, 1) 'Get the first character
word = word.Remove(0, 1) 'Remove the first character
input.Text = mychar
word = word & mychar
output.Text = word
This is my code for shifting 1 letter.
I.E. for the word 'Star Wars', it currently shifts 1 letter, and says 'tar WarsS'
How can I make this move 3 characters to the end? Like in the sample image.
intNumChars = input.text
output.text = mid(word,4,len(word)) & left(word,3)
I wanted it to be easy for you to read but you can set the intNumChars variable to the value in your text box and replace the 4 with intNumChars + 1 and the 3 with intNumChars.
The mid() function can return a section of text in the middle of a string mid(string,start,finish). The len() function returns the length of a string so that the code will work on texts that are different lengths. The left function returns characters from the left() of a string.
I hope this is of some help.
You could write a that as a sort of permute, which maps each char-index to a new place in the range [0, textLength[
In order to do that you'll have to write a custom modulus as the Mod operator is more a remainder than a modulus (from a mathematical point of view, regarding how negative are handled)
With that you just need to loop over your string indexes and map each one to it's "offsetted" value modulo the length of the text
' Can be made local to Shift method if needed
Function Modulus(dividend As Integer, divisor As Integer) As Integer
dividend = dividend Mod divisor
Return If(dividend < 0, dividend + divisor, dividend)
End Function
Function Shift(text As String, offset As Integer) As String
' validation omitted
Dim length = text.Length
Dim arr(length - 1) As Char
For i = 0 To length - 1
arr(Modulus(i + offset, length) Mod length) = text(i)
Next
Return new String(arr)
End Function
That way you can easily handle negative values or values greater than the length of the text.
Note, the same thing is possible with a StringBuilder instead of an array ; I'm not sure which one is "better"
Function Shift(text As String, offset As Integer) As String
Dim builder As New StringBuilder(text)
Dim length = text.Length
For i = 0 To length - 1
builder(Modulus(i + offset, length) Mod length) = text(i)
Next
Return builder.ToString
End Function
Using Gordon's code did the trick. The left function visual studio tried to create a stub of the function, so I used the fully qualified function name when calling it. But this worked perfectly.
intNumChars = shiftnumber.Text
output.Text = Mid(word, intNumChars + 1, Len(word)) & Microsoft.VisualBasic.Left(word, intNumChars)
n = 3
output.Text = Right(word, Len(word) - n) & Left(word, n)

Break string up

I have a string that has 2 sections broken up by a -. When I pass this value to my new page I just want the first section.
An example value would be: MS 25 - 25
I just want to show: MS 25
I am looking at IndexOf() and SubString() but I can't find how to get the start of the string and drop the end.
This might help:
http://www.homeandlearn.co.uk/net/nets7p5.html
Basically the substring method takes 2 parameters. Start position and length.
In your case, the start position is 0 and length is going to be the position found by the IndexOf method -1.
For example:
Dim s as String
Dim result as String
s = "MS 25 - 25"
result = s.SubString(0, s.IndexOf("-")-1)
You could use the Split function on the hyphen.
.Split("-")
If you want to stay away from Split, you could use SubString
yourString.Substring(0, yourString.IndexOf("-") - 1)
EDIT
The above code will fail in the instances where there is no hyphen at all or the hyphen is in the beginning of the string, also when there are no spaces surrounding the hyphen, the full leading substring will not be returned. Consider using this for safety:
Dim pos As Integer
Dim result As String
pos = yourString.IndexOf("-")
If (pos > 0) Then
result = yourString.Substring(0, pos)
ElseIf (pos = 0) Then
result = String.Empty
Else
result = yourString
End If

Substring starting at specific character count

How would you select the last part of a string starting at a specific character count.
For example I would like to get all text after the 3rd comma. but I get an error saying
"StartIndex cannot be less than zero."
Dim testString As String = "part, description, order, get this text, and this text"
Dim result As String = ""
result = testString.Substring(testString.IndexOf(",", 0, 3))
Heres my two cents:
string.Join(",", "aaa,bbb,ccc,ddd,eee".Split(',').Skip(2));
The code "testString.IndexOf(",", 0, 3)" does not find the 3rd comma. It find the first comma starting at position 0 looking at the first 3 positions (i.e. character positions 0,1,2).
If you want the part after the last comma use something like this:
Dim testString As String = "part, description, order, get this text"
Dim result As String = ""
result = testString.Substring(testString.LastIndexOf(",") + 1)
Note the +1 to move to the character after the comma. You should really also find the index first and add checks to confirm that the index is not -1 and index < testString.Length too.
Alternatives(I assume you want all the text after last comma):
Using LastIndexOf:
' You can add code to check if the LastIndexOf returns a positive number
Dim result As String = testString.SubString(testString.LastIndexOf(",")+1)
Regular Expressions:
Dim result As String = Regex.Replace(testString, "(.*,)(.*)$", "$2")
The third argument of indexOf is the number of charcters to search. You are searching for , starting at 0 for 3 characters - that is searching the string par for a comma which does not exist so the returned index is -1, hence your error. I think that you would need to use some recursion:
Dim testString As String = "part, description, order, get this text"
Dim index As Int32 = 0
For i As Int32 = 1 To 3
index = testString.IndexOf(","c, index + 1)
If index < 0 Then
' Not enough commas. Handle this.
End If
Next
Dim result As String = testString.Substring(index + 1)
The IndexOf function only finds the "First" of the specified character. The last parameter (in your case 3) specifies how many characters to examine and not the occurence.
Refer to Find Nth occurrence of a character in a string
The function specified here finds the Nth occurance of a character. Then use the substring function on the occurance returned.
Alternative , you can also use regular expression to find the nth occurance.
public static int NthIndexOf(this string target, string value, int n)
{
Match m = Regex.Match(target, "((" + value + ").*?){" + n + "}");
if (m.Success)
{
return m.Groups[2].Captures[n - 1].Index;
}
else
{
return -1;
}
}
I think this is what you are looking for
Dim testString As String = "part, description, order, get this text"
Dim resultArray As String() = testString.Split(New Char() {","c}, 3)
Dim resultString As String = resultArray(2)

How to split string in group in vb.net

i'm amol kadam,I want to know how to split string in two part.My string is in Time format (12:12).& I want to seperate this in hour & minute format.the datatype for all variables are string. for hour variable used strTimeHr & for minute strTimeMin .I tried below code but their was a exception "Index and length must refer to a location within the string.
Parameter name: length"
If Not (objDS.Tables(0).Rows(0)("TimeOfAccident") Is Nothing Or objDS.Tables(0).Rows(0)("TimeOfAccident") Is System.DBNull.Value) Then
strTime = objDS.Tables(0).Rows(0)("TimeOfAccident") 'strTime taking value 12:12
index = strTime.IndexOf(":") 'index taking value 2
lastIndex = strTime.Length 'Lastindex taking value 5
strTimeHr = strTime.Substring(0, index) 'strTime taking value 12 correctly
strTimeMin = strTime.Substring(index + 1, lastIndex) 'BUT HERE IS PROBLEM OCCURE strTimeMin Doesn't taking any value
Me.NumUpDwHr.Text = strTimeHr
Me.NumUpDwMin.Text = strTimeMin
End If
The simplest way (assumming that you can ensure the format) is to use a split:
dim strTime as string = objDs.Tables(0).Rows(0).("TimeOfAccident")
dim timeParts() as string = split(strTime,":")
dim strTimeHr as string = timeParts(0)
dim strTimeMn as string = timePartS(1)
you'll also want some error handling to check for formatting and that the split generates the array with at least two elements and what not.
EDIT: After looking more closely at your code, I see the cause of your error.
You have this code:
lastIndex = strTime.Length
strTimeHr = strTime.Substring(0, index)
strTimeMin = strTime.Substring(index + 1, lastIndex)
With that last line giving the error.
The reason that you're getting that error is that strings (and other arrays) in VB.Net are ZERO BASED. Which is why in the strTimeHr field, you're starting at position 0. Length gives you the count, which since the array is zero-based, means the count will be one more than available indexes.
I.e. the last element in a zero based array is the length of the array minus 1.
Therefore, changing your original code to this:
lastIndex = strTime.Length - 1
strTimeHr = strTime.Substring(0, index)
strTimeMin = strTime.Substring(index + 1, lastIndex)
will work as well.
string s = "12:13";
DateTime dt = DateTime.Parse(s);
Console.Write(dt.Hour + " " + dt.Minute);
Try something like (String.Split Method )
Dim str As String = "12:13"
Dim strHr = str.Split(":")(0)
Dim strMin = str.Split(":")(1)
Is the datatype of the column "TimeOfAccident" a DateTime? If so, then the simplest solution would be something like:
'Using LINQ to convert the value to a nullable datetime.
Dim timeOfAccident As Nullable(Of DateTime) = dt.Rows(0).Field(Of Nullable(Of DateTime))("TimeOfAccident")
If timeOfAccident.HasValue Then
Me.NumUpDwHr.Text = timeOfAccident.Hour
Me.NumUpDwMin.Text = timeOfAccident.Minute
End If
If the column "TimeOfAccident" is a string, then you can do something like:
Dim timeOfAccidentString As String = dt.Rows(0).Field(String)("TimeOfAccident")
If Not String.IsNullOrEmpty(timeOfAccidentString) Then
Dim accidentTime As DateTime = DateTime.Parse(timeOfAccidentString)
Me.NumUpDwHr.Text = timeOfAccident.Hour
Me.NumUpDwMin.Text = timeOfAccident.Minute
End If