2014-02-05 56 views
-2

一个字符的位置我的代码是这样的:C#得到字符串

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

回答

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

这不会处理,如果你的性格是在零位和其他一些条件,你必须弄清楚他们。

+0

谢谢你,如果我想设置的,而不是“CH”像TextBox1中的字符串.text,我怎么能转换成char? – Sedax

+0

那么... textbox1.Text是一个完整的字符串属性。你必须将它转换为一个字符数组('Textbox1.Text.ToCharArray()')并在'for'循环中迭代 – Brandon

+0

谢谢布兰登。 – Sedax

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

} 
+0

感谢凯里,但又一次,我如何从字符串中搜索字符串,而不是char'c'。 ? – Sedax

+0

正如我在回答中所指出的那样:**阅读文档**您甚至不想自助。 'IndexOf()'有几个*重载*,可以使用'char'或'string'。另请参阅'string.IndexOfAny()',它在字符列表的字符串中找到第一个匹配项。) –