user222427
user222427

Reputation:

C# split string of first character occurrence

I thought this was simple but this is just kicking my butt.

I have this string 21. A.Person I simply want to get A.Person out of this.

I try the following but I only get 21

string[] pName = values[i, j].ToString().Split(new char[] { '.' }, 2);
pName[1] ???

values[i, j].ToString() = 21. A.Person and yes I've verified this.

Upvotes: 1

Views: 7497

Answers (5)

Randy James
Randy James

Reputation: 1480

Everyone is giving you alternate solutions when yours should work. The problem is that values[i, j] must not equal 21. A.Person

I plugged it into a simple test..

    [Test]
    public void junk()
    {
        string[] pName = "21. A.Person".Split(new char[] { '.' }, 2);
        Console.WriteLine(pName[1]);
    }

What does it print? A.Person (With the space in the front, because you didn't trim the space)

Upvotes: 4

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

Try this:

var substr="";
var indedx = yourString.IndexOf('.');
if(index>-1)
   substr = yourString.Substring(index);
substr=substr.Trim();

For string "21. A.Person" should return "A.Person"

Upvotes: 5

Swift
Swift

Reputation: 1881

Try something like that:

  var str = "21. A.Person";
  var index = str.IndexOf('.') +1;
  var substr = str.Substring(index, str.Length - index);

Upvotes: 1

Nicolas Tyler
Nicolas Tyler

Reputation: 10552

string pName = values[i, j].ToString().Substring(values[i, j].ToString().IndexOf('.')+1);

Upvotes: 1

Chris
Chris

Reputation: 2952

I would use substring() with the position of the first '.' as your start point:

var name = sourceString.Substring(sourceString.IndexOf('.'));

Upvotes: 2

Related Questions