Marcus Aurelio
Marcus Aurelio

Reputation: 153

How do I split a string and remove whitespace from the parts?

I am trying to create a console app. The user enters a statement like:

create column in table with values {Name, Address, Age, Telephone} ./

What I am hoping to do is take the line above and create variables:

var v1= create;
var v2 = column
var v3 = table;
var v4 = Name;
var v5 = Address;
var v6 = Age;
var v7 = Telepone;
var v8 = ./;

So that I can use these values later for conditional statements. I have tried this:

string[] split = command.Split(' ',',', '{','}');

But it's not giving me what I need; there are white spaces. Does anyone know how I can achieve what I am trying to do? I'm quite new to c# so struggling with this.

Upvotes: 0

Views: 72

Answers (2)

Owen Pauling
Owen Pauling

Reputation: 11841

Use the String.Trim method.

List<string> parts = command.Split(' ', ',', '{', '}').Select(p => p.Trim()).ToList();

Upvotes: 1

Backs
Backs

Reputation: 24903

Add StringSplitOptions:

string[] split = command.Split(new char[]{' ',',', '{','}'}, StringSplitOptions.RemoveEmptyEntries);

Upvotes: 2

Related Questions