C# get position of a character from string

后端 未结 2 2036
轻奢々
轻奢々 2021-01-29 09:37

My code is this:

 string dex = \"ABCD1234\";
 string ch = \"C\";
 string ch1, ch2;
    if (dex.Contains(ch))
    {
       string n = Convert.ToChar(dex);
                


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-01-29 10:03

    You might want to read the documentation on System.String and its methods and properties:

    The method you want is IndexOf():

    string s = "ABCD1234" ;
    char   c = 'C' ;
    
    int offset = s.IndexOf(c) ;
    bool found = index >= 0 ;
    if ( !found )
    {
      Console.WriteLine( "string '{0}' does not contain char '{1}'" , s , c ) ;
    }
    else
    {
      string prefix = s.Substring(0,offset) ;
      string suffix = s.Substring(offset+1) ;
    
      Console.WriteLine( "char '{0}' found at offset +{1} in string '{2}'." , c , offset , s ) ;
      Console.WriteLine( "The substring before it is '{0}'."             , prefix ) ;
      Console.WriteLine( "The substring following it is '{0}'."          , suffix ) ;
    
    }
    

提交回复
热议问题