我的代码是:
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);
}
我想将字符串转换为数组,但我不能这样做,我无法检索'ch'字符串的位置以及它之间的内容。
输出应为:
MessageBox.Show("C is on 3rd place and is between B and D");
答案 0 :(得分:4)
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]));
如果你的角色处于零位和其他一些条件下,你将无法解决这个问题。
答案 1 :(得分:1)
您可能需要read the documentation on System.String
及其方法和属性:
您想要的方法是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 ) ;
}