简体   繁体   中英

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.

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"

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)

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

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

Try something like that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM