C#从字符串获取字符的位置 [英] C# get position of a character from string

查看:169
本文介绍了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'字符串的位置及其之间的位置.

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.

输出应为:

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

推荐答案

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.

这篇关于C#从字符串获取字符的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆