Extract 2 words from a string - vb.net

im working with a receipt layout and trying to divide up a products descriptiontext into 2 lines if its longer then 24 characters.
my first solution was something like this:
If Row.Description.Length >= 24 Then
TextToPrint &= Row.Description.Substring(0, 24) & " $100"
TextToPrint &= Row.Description.Substring(24) & vbNewLine
else
TextToPrint &= Row.Description & filloutFunction(Row.Description.length) &" $100" & vbNewLine
end if
but that gives this result.
A product with a long na $100
me that doesn't fit
I cant figure out how to make a function to divide the description to look like we normaly see it.
A product with a long $100
name that doesn't fit
hope i made myself clear /:

If its greater than 24 then look for a space character from point 23 decrementally. Once you find it, split the string on that position. That 'column' system you have looks pretty nasty though - where is this output going, screen?

My first shot,
private static List<string> SplitSentence(string sentence, int count)
{
if(sentence.Length <= count)
{
return new List<string>()
{
sentence
};
}
string extract = sentence.Substring(0, sentence.Substring(0, count).LastIndexOfAny(new[]
{
' '
}));
List<string> list = SplitSentence(sentence.Remove(0, extract.Length), count);
list.Insert(0, extract.Trim());
return list;
}
and so :
string sentence = "A product with a long name that doesn't fit";
List<string> sentences = SplitSentence(sentence, 24);
sentences[0] = sentences[0] + " $100";
I think it's possible to optimize.

Something like this should work:
Dim yourString = "This is a pretty ugly test which should be long enough"
Dim inserted As Boolean = False
For pos As Integer = 24 To 0 Step -1
If Not inserted AndAlso yourString(pos) = " "c Then
yourString = yourString.Substring(0, pos + 1) & Environment.NewLine & yourString.Substring(pos + 1)
inserted = True
End If
Next

Related

Add text before specific characters

str as String = " " +"thisrocks" + " "
and strArray(0) = 123456sdv :'++':
so i want to add str before the :'++':, and then
strArray(0) = 123456sdv thisrocks :'++':
Is it possible ?
What could I do to search for it ? Regex maybe ?
str and strArray will already be there from previous codes. I just want to combine it int he right place.
Using the space in between will not be helpful as the strArray(0) could also be, dsf dsv dsgvsvs svs svssd bdsb sbdfb bsbb sb s sbsfbfsbsbfs :'++': and so on.
I can't control it as they come like that from previous codes and there is no way to fix them :/
I can't generalize the question since it is not clear enough, for this occasion you can use the following code to insert a string in between these two words
Dim str As String = " " + "thisrocks" + " "
Dim strArray(10) As String
strArray(0) = "123456sdv :'++':"
strArray(0) = strArray(0).Replace(":'++':", str & ":'++':")
Output will be
"123456sdv thisrocks :'++':"
Note:
this will work as, replace :'++': with & str and add :'++': to it so :'++': will stay their for the next replacement.
You can use String.IndexOf to find where the marker :'++': is and String.Insert to insert the required data:
Dim sample As String = "123456sdv :'++':"
Dim insertData As String = " thisrocks "
Dim marker As String = ":'++':"
Dim insertPos As Integer = sample.IndexOf(marker)
If insertPos >= 0 Then
sample = sample.Insert(insertPos, insertData)
End If
Console.WriteLine(sample) ' outputs "123456sdv thisrocks :'++':"

My For Loop skips my IF statement

I wonder if anyone can help. I am making a program that will convert Text to ASCII. However, I want my program to ignore spaces. Hence, "IT WAS A" should look like this: 7384 876583 65
When I use the Step Into Feature of VB I can see that my For loop is skipping my IF statement which should be giving me my spaces. I don't understand why. As you can probably tell, I am a beginner so any specific help would be greatly appreciated. My code looks like this:
Dim PlainText, ConvertedLetter As String
Dim LetterToConvert As Char
Dim AscNumber, Counter As Integer
ConvertedLetter = ""
PlainText = txtPlain.Text
For Counter = 1 To Len(PlainText)
LetterToConvert = Mid(PlainText, Counter, 1)
If PlainText = " " Then
ConvertedLetter = " "
Else : AscNumber = Asc(LetterToConvert)
ConvertedLetter = ConvertedLetter & AscNumber
End If
Next
txtAscii.Text = ConvertedLetter
Because you're comparing PlainText, which is the whole string, to " ". It would need to be:
If LetterToConvert = " " Then ....
Try this:
Dim PlainText, ConvertedLetter As String
ConvertedLetter = ""
PlainText = "IT WAS A"
For Each c As Char In PlainText 'iterate through each character in the input
If c <> " " Then ' check whether c is space or not
ConvertedLetter &= Asc(c).ToString()' ascii value is taken if c<>" "
Else
ConvertedLetter &= " " ' c is space means add a space
End If
Next
MsgBox(ConvertedLetter) ' display the result
You will get the output as
7384 876583 65

How could I get the first and last letters from a string?

How can I get my program to take the first and last letters from an entered string?
Example: "I've been told I am a noob!"
Output: "IebntdIaman!"
I tried to use Split with no luck.
Try something like this. since you have a couple of single character words I used a conditional in order to get your desired output. I also am using the String.Split method that removes empty entries in order to prevent a zero length item, then I am taking the result and using the String.Substring Method to parse out your starting and ending chars.
Sub Main()
Dim splitChar As String() = {" "}
Dim example As String = " I've been told I am a noob!"
Dim output As String = ""
Dim result As String() = example.Split(splitChar, StringSplitOptions.RemoveEmptyEntries)
For Each item In result
If item.Length > 1 Then
output += item.Substring(0, 1) & item.Substring(item.Length - 1, 1)
Else
output += item.Substring(0, 1)
End If
Next
Console.WriteLine(output)
Console.ReadLine()
End Sub
This works nicely:
Dim example As String = "I've been told I am a noob!"
Dim result = New String( _
example _
.Split(" "c) _
.SelectMany(Function (w) _
If(w.Count() = 1, _
new Char() { w(0) }, _
New Char() { w.First(), w.Last() })) _
.ToArray())
'IebntdIaman!

VBNewLine after certain number of characters AND a given character

All,
I developed a formatting/comma-delimiting application that turns a long string of numbers into the correct format for SQL queries.
For example:
101
102
103
104
105
Becomes:
('101','102','103','104','105')
It's a very useful tool, but lets say there are 500 different values to format. This creates a very long line in SQL server.
I've been searching on the internet, but I have yet to find something that can accomplish my question:
How do I word wrap to 100 characters per line, but not breaking up the format:
('Value1','Value2','Value3')
Please let me know if I need to explain further. Thanks for the help!
This will convert the "long string of numbers" into sql format with a lineLength parameter:
Public Function ConvertToSqlParameter(input As String, lineLength As Integer) As String
Dim sb = New StringBuilder("(")
Dim len = 0
For Each s In input.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
If len >= lineLength Then
sb.Append(Environment.NewLine)
len = 0
End If
Dim str = "'" + s + "',"
len += str.Length
sb.Append(str)
Next
sb.Length -= 1
sb.Append(")")
Return sb.ToString()
End Function

How to convert bit number to digit

I'm working to create an Excel macro using VBA to convert bit strings to numbers. They are not binary numbers, each '1' stands for it's own number.
e.g: 1100000000000000000010001
from the left, the first bit represents "1", the second bit represents "2", third bit represents "0", and so on. The total quantity of bits in each string is 25.
I want VBA to convert it and show results like so: 1, 2, 21, 25.
I tried using Text to Columns but was not successful.
Try something like this:
Sub Execute()
Dim buff() As String
Dim i As Integer, total As Double
buff = Split(StrConv(<theString>, vbUnicode), Chr$(0))
total = 0
For i = 0 To UBound(buff)
Debug.Print (buff(i))
'total = total + buff(i) * ??
Next i
End Sub
Consider:
Public Function BitPicker(sIn As String) As String
For i = 1 To Len(sIn)
If Mid(sIn, i, 1) = 1 Then
BitPicker = BitPicker & i & ","
End If
Next
BitPicker = Mid(BitPicker, 1, Len(BitPicker) - 1)
End Function
Another non-VBA solution, based on the OP' initial approach and with a layout designed to facilitate multiple 'conversions' (ie copy formulae down to suit):
Does this have to be VBA? Give a data setup like this:
The formula in cell B4 and copied down to B33 is:
=IF(ROWS(B$3:B3)>LEN($B$1)-LEN(SUBSTITUTE($B$1,"1","")),"",FIND("#",SUBSTITUTE($B$1,"1","#",ROWS(B$3:B3))))
The formula cells are formatted as General and the the Bit String cell (B1) is formatted as Text.
Try this:
Function ConvertMyRange(Rng As Range) As String
Dim MyString As String
MyString = Rng.Text
Dim OutPutString As String
For i = 1 To Len(MyString)
If Mid(MyString, i, 1) = "1" Then OutPutString = OutPutString & ", " & i
Next i
' Get rid of first ", " that was added in the loop
If Len(OutPutString) > 0 Then
OutPutString = Mid(OutPutString, 2)
End If
ConvertMyRange = OutPutString
End Function
For your input, the output is 1, 2, 21, 25