Split String

StewartBW 1,145 Reputation points
2024-06-27T13:40:42.97+00:00

Hello

This code does not remove space only fields, how to discard space only fields?

Dim MyString As String = ";full; ;title"
Dim MyFinal As String() = MyString.Split(New Char() {";"c}, StringSplitOptions.RemoveEmptyEntries)

The second is a single space and unwanted.

Thanks :)

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,732 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Anonymous
    2024-06-27T17:36:36.1933333+00:00

    Hi

    The 'single space' is in fact not an empty entry, so, is not removed. Try this as a possible solution:

    		Dim MyString As String = ";full; ;title"
    		Dim MyFinal As String() = MyString.Split(New Char() {";"c, " "c}, StringSplitOptions.RemoveEmptyEntries)
    
    
    1 person found this answer helpful.

  2. Jiachen Li-MSFT 32,051 Reputation points Microsoft Vendor
    2024-06-28T02:40:24.2966667+00:00

    Hi @StewartBW

    You can use the Where method from LINQ along with Trim to remove fields that contain only spaces.

    Imports System.Linq
    
    Dim MyString As String = ";full; ;title"
    Dim MyFinal As String() = MyString.Split(New Char() {";"c}, StringSplitOptions.RemoveEmptyEntries).Where(Function(s) s.Trim() <> "").ToArray()
    
    

    Best Regards.

    Jiachen Li


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.