How to find the space using substring to display initials - vb.net

The part of the program I'm trying to write is supposed to take the users input, which is their name, and in a listbox spit out their initials. I have so far:
Dim initials As String
Dim indexspace As Integer
initials = name.Substring(0, 1)
indexspace = name.IndexOf(" ")
lstInvoice.Items.Add(String.Format(strFormat, "Invoice ID", initials & space))
When I run the program, I can get the first initial to pop up, but I am not certain how to get the second to pop up.
Thank you very much for your assistance on this matter, it is much appreciated

Q: How do I find a space (" ") in a string with VB.Net?
A: String.IndexOf (" ");
Q: How do I find subsequent spaces in the string?
A: Extract the substring of everything to the right of the first space you found.
Then do an ".IndexOf (" ")" of that substring.
Until you get to the end of the string, or until you get bored :)

I apologize for not writing it in VB but I am more familiar with C#. There is no reason to look for the index of a space. Just split the string on the space and then pull the first letter of each of the results in the array. For simplicity, I made an assumption that it was only two words in the string but you could loop through the array of results to put out all the initials if they included a middle name:
string name = "Test User";
string[] nameParts = name.Split(' ');
string initials = nameParts[0].Substring(0, 1) + nameParts[1].Substring(0, 1);
VB Version:
Dim name As String = "Test User"
Dim nameParts As String() = name.Split(" ")
Dim initials As String = nameParts(0).Substring(0, 1) & nameParts(1).Substring(0, 1)
Again this is a very simplistic approach to what you are asking. As #paxdiablo pointed out in his comments there are variations of names that will not match this pattern but you know you're program.

Related

Override String in TextBox

I have 3 text boxes on my form: Surname, First Name and Middle Name. I want to override my string. It looks like this:
...<<<<<<<<<<<<<<<<... (Length = 36)
If I save a value and the text boxes contain Surname:Bergs, First Name:John Paul, Middle Name:Dale, and for sample purpose I want to display this in MessageBox, and should be like this
D<aleBergs<<John<Paul<<<<<<<<
I have 2 objectives in this Question.
How can I get the Text box specific value and display it on my string?
If Text Box Contains space how can I turn it into < value?
Update
I solved Second Problem fix using this String.Replace()
Dim str As String = "John Paul"
Dim str2 As String = str.Replace(" ", "<")
MessageBox.Show(str2)
Use pre-fabricated string to have clear format
Dim outputFormat As String = "{0} {1} {2}"
MessageBox.Show(string.Format(outputFormat, txtMid.Text, txtFirst.Text, txtLast.Text))
You can also use format like {0, 10} or {0,-10} to get fixed positions, like this
|John......|
|......John|
Where dots stand for spaces
If i'm right, You can get textbox inputs to separate string variables and concatenate them into one string variable or you can get all textbox values to one string variables like
Dim AllStrings As String
AllStrings = MiddleTextBox.Text &" "& FirstTextBox.Text &" "& LastTextBox.Text
Then you can replace spaces by using Replace Method.
AllStings = AllStrings.Replace(" ","<")
Hope this will helpful to you.

remove from String in VB

I have inserted a option in Dorpdown as follows
<option>إختر </option>
When I select this text from server side on any event I get this value
"إختر       ‎"
Now I want to replace this white space in the string. I have tried replace method of String class. But its not working.
str = str.replace(" ","")
Plz suggest
What you should do first is decode the HTML, such that text like but also & are converted to their textual counterparts (" " and "&"). You can do this with: WebUtility.HtmlDecode. Next you can use String.Trim to remove leading and tailing spaces.
Example:
string s = "إختر ";
string r = WebUtility.HtmlDecode(s).Trim();
Or the VB.NET equivalent:
Dim s As String = "إختر "
Dim r As String = WebUtility.HtmlDecode(s).Trim()
Evidently you can try to convert to spaces yourself. But there are examples where it is not that evident and your transcoder can get confused or decode strings the wrong way. Furthermore if in the future the people at W3C change their minds about how to encode text in HTML/XML, then your program will still work.
String.Trim will remove all kinds of white-space including spaces, new lines, tabs, carriage returns, etc. If you only want to remove spaces, you can use: .Trim(' '). Then you specify only to remove the given list of characters (here only ' ').
If you want to remove leading or trailing white-spaces from a string you just need to use String.Trim, but you have to re-assign the return value to the variable since strings are immutable:
string text = "إختر       ‎";
text = text.Trim();
Note that you can also use TrimEnd in this case.
If you want to remove only space characters(not also tabs or new-line characters which are also white-spaces) use:
text = text.Trim(' ');
If you instead want to remove all spaces from a string you could do:
text = text.Replace(" ", "");
I think maybe your code is something like this
Dim str As String = "إختر "
str.Replace(" ", "")
But actually you should
Dim str As String = "إختر "
str = str.Replace(" ", "")
I have just had a similar problem.
It turns out, that this nbsp character is Chr(160) from the ASCII table. Thus, something like this is quite meaningful, for all the cases. It works, on a selected area:
Public Sub remove_space_in_string()
Dim r_range As Range
For Each r_range In Selection
r_range = Trim(r_range)
r_range = Replace(r_range, vbTab, "")
r_range = Replace(r_range, " ", "")
r_range = Replace(r_range, Chr(160), "")
Next r_range
End Sub

How to get the first value in textbox

how can i get the first value in a text box and place it to a label. Example, I want to get the word "look" in the textbox that I input was "look like".
You could use substring, this will split the string or aka your textbox.
This takes two params, The starting index of the string and the 2nd param is the length. I have put str.indexof in the 2nd param to get the index of where the space is.
dim str as string
Label1.Text = str.Substring(0, str.IndexOf(" "))
This code is not tested, I only used visual basic for a little bit when i was 12.
you can simply split the value by " " space and take the first one from result array
if(!String.IsNullOrEmpty(textBox1.Text))
{
lable1.Text = textBox1.Text.Split(" ").first();
}
textboxValue = Textbox.Text;
str = textboxValue.Split(" ").first();

VB.NET Get text in between Quotations or other symbols

I want to be able to extract a string in between quotation marks or parenthesis etc. to a variable. For example my text might be "Hello there "Bob" ". I want to extract the text "Bob" from in between the two quotation marks and put it in the string "name" for later use. The same would be for "Hello there (Bob)". How would I go about this? Thanks.
=======EDIT======
Sorry, I worded this poorly. Ok, so lets say I have a textbox(Textbox1) and a button. If the user inputs the text: MsgBox "THIS IS MY MESSAGE" I want that when the Button is pressed, only the text THIS IS MY MESSAGE is displayed.
This is a solution very simple:
Dim sAux() As String = TextBox1.Text.Split(""""c)
Dim sResult As String = ""
If sAux.Length = 3 Then
sResult = sAux(1)
Else
' Error or something (number of quotes <> 2)
End If
There are basically three methods -- regular expressions, string.indexof and substring and finally looping over the characters one by one. I would avoid the latter as it is just reinventing the wheel. Whether to use regexs or indexof depends upon the complexity of your requirements and data. Indexof is a bit wordy but fairly straightforward and possibly just what you want in this case.
Dim str as String = "Hello there ""Bob"""
Dim startName as Integer
Dim endName as Integer
Dim name as String = ""
startName = str.IndexOf("""")
endName = str.Indexof("""", If(startName > 0, startName,0))
If (endName>startName) Then
name = str.SubString(startName, endName)
End If
If you need to do this for arbitrary symbols, then you want regexs.

Remove excess white space from string

I want to remove the excess white spaces using VB.net
ex.
"The Quick Brown Fox"
I want output
"The Quick Brown Fox"
Thanks,
inchika
You can use a simple regular expression for that:
Dim cleaned As String = Regex.Replace(input, "\s{2,}", " ")
I realize that this question is fairly old, but there is another option that doesn't involve Regex, or manually looping through the string and replacing:
Private Function StripSpaces(input As String) As String
Return String.Join(" ", input.Split(New Char() {}, StringSplitOptions.RemoveEmptyEntries))
End Function
And the C# equivalent:
private string StripSpaces(string input)
{
return string.Join(" ", input.Split((char[])null, StringSplitOptions.RemoveEmptyEntries));
}
Using a "null" value as the split character on String.Split causes the split character to be all characters that return true if they were sent to Char.IsWhiteSpace. Therefore, calling the method this way will split your string on all whitespace, remove the empty strings, then re-join it together with a single space in between each split array element.
What you actually want is to compact any multiple white space to a single space, and one way to do that is to search for two spaces and replace them with a single space, until there are no two adjascent spaces left, something like this:
Dim myString As String = "The Quick Brown Fox"
While myString.IndexOf(" ") <> -1
myString = myString.Replace(" ", " ")
End While
Console.WriteLine(myString)
However, this is not fool-proof because of some ideosyncracies of .net strings, this might go into an endless loop, but only for some very odd inputs.
EDIT: This particular processing is faster (and simpler) using a regular expression, as pointed in the othe answers.
Try this:
Dim output As String = Regex.Replace("The Quick Brown Fox","\\s+" , " ")