【问题标题】:C# get position of a character from stringC#从字符串中获取字符的位置
【发布时间】:2014-02-05 18:58:34
【问题描述】:

我的代码是这样的:

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

【问题讨论】:

    标签: c# string position char


    【解决方案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]));
    

    如果你的角色在零位和其他一些情况,这将无法处理,你必须弄清楚它们。

    【讨论】:

    • 谢谢,如果我想设置而不是 'ch' 像 textbox1.text 这样的字符串,我该如何将其转换为 char?
    • 嗯... textbox1.Text 是一个完整的字符串属性。您必须将其转换为字符数组 (Textbox1.Text.ToCharArray()) 并在 for 循环中迭代它们
    【解决方案2】:

    您可能想要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 ) ;
    
    }
    

    【讨论】:

    • 谢谢凯莉,但再一次,我怎样才能从那个字符串中搜索一个字符串,而不是 char 'c'。 ?
    • 正如我在回答中指出的那样:阅读文档。您甚至没有试图帮助自己。 IndexOf() 有几个重载,它们采用charstring。还要阅读string.IndexOfAny(),它会在字符列表的字符串中找到第一个出现的位置。)
    猜你喜欢
    • 2012-10-22
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 2012-01-26
    • 1970-01-01
    相关资源
    最近更新 更多