C#字符串操作思路要求

杜普·伯格

我似乎找不到找到用字符串完成任务的“好方法”

假设我有一个字符串,其值为“ Take Chocolate”,并且使用.Contains方法检测该字符串中是否包含字符串“ cola”,并且该字符串中确实包含“ cola”。我想要一种方法让程序获取“可乐”中“ c”之前的字符和“ a”之后的字符,以检查字符是否均为空白。任何想法如何解决这个问题?任何提示或想法都太棒了!

附言:我正在制作一个相当广泛的基于文本的冒险游戏。

Mybirthname
    static void Main(string[] args)
    {
        string s = "Take Chocolate";
        string searchString = "cola";

        int beginIndex = 0;
        int endIndex = 0;

        if (s.Contains(searchString))
        {
            beginIndex = s.IndexOf(searchString, 0, s.Length);
            endIndex = beginIndex + searchString.Length;
        }

        if(endIndex < s.Length)
        {
            Console.WriteLine(s[endIndex + 1]);

        }
        else
        {
            Console.WriteLine("There is no character after" + searchString);
        }

        if(beginIndex > 0)
            Console.WriteLine(s[beginIndex - 1]);
        else
            Console.WriteLine("There is no character before" + searchString);

    }

这是执行此操作的小程序。希望能帮助到你。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章