Samiul
Samiul

Reputation: 35

How to remove characters from a string to get the desired format?

I have a string representation exactly like 'ComputerName -- IPAddress'; i.e:

'samarena -- 192.168.1.97'

. I want to get only the 'ComputerName' part from the actual representation by removing other characters. I'm actually quite beginner in using string.FormatMethods() .

Please help me out.

Thanks.

Upvotes: 1

Views: 164

Answers (5)

VoodooChild
VoodooChild

Reputation: 9784

Try this:

char [] chars = {'-'};
string test = "samarena -- 192.168.1.97";

//computerName array will have the Computer Name at the very first index (it is a zero based index    
string[] computerName = test.Split(chars,StringSplitOptions.RemoveEmptyEntries);
//computerName[0] is your computerName

Upvotes: 0

Maciej Hehl
Maciej Hehl

Reputation: 7995

If You are sure there is always a substring " -- " after the part You want, You can do this

myString.Substring(0, myString.IndexOf(" -- "))

Or use a shorter part of " -- ".

Upvotes: 0

Tomas
Tomas

Reputation: 3434

This should do it.

var yourString = "samarena -- 192.168.1.97";
var indexOfDash = yourString.IndexOf("-");
var yourComputerName = yourString.SubString(0, indexOfDash).Trim();

But the other answers using Trim are better :)

This'd be the totally imperative way.

Upvotes: 0

Sam Holder
Sam Holder

Reputation: 32954

you could split the string on ' -- ' and then use the first part

Upvotes: 0

Kelsey
Kelsey

Reputation: 47766

This should do it:

string test = "samarena -- 192.168.1.97";
var result = test.Split(new string[] { "--" }, StringSplitOptions.None)[0].Trim();

Result will equal samarena

Upvotes: 2

Related Questions