C# get position of a character from string

感情迁移 提交于 2021-02-05 12:21:55

问题


My code is this:

 string dex = "ABCD1234";
 string ch = "C";
 string ch1, ch2;
    if (dex.Contains(ch))
    {
       string n = Convert.ToChar(dex);
       MessageBox.Show(ch + "  is on " + n + " place and is between " + ch1 + " and " + ch2);
    }

I wanted to convert the string into array but i can't do it and i can't retrieve the position of the 'ch' string and what's between it.

The output should be:

MessageBox.Show("C is on 3rd place and is between B and D");

回答1:


string aS = "ABCDEFGHI";
char ch = 'C';
int idx = aS.IndexOf(ch);
MessageBox.Show(string.Format("{0} is in position {1} and between {2} and {3}", ch.ToString(), idx + 1, aS[idx - 1], aS[idx + 1]));

This wont handle if your character is at position zero and some other conditions, you'll have to figure them out.




回答2:


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 ) ;

}


来源:https://stackoverflow.com/questions/21586107/c-sharp-get-position-of-a-character-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!