C# 如何获取字符串中单词的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15582441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:16:38  来源:igfitidea点击:

How to get INDEX of word inside a string

c#string

提问by Bryan Arbelo - MaG3Stican

I am trying to get the INDEX of a word inside a string and if possible also to delete all the characters previous to this word in the string, it would make my life easier.

我正在尝试获取字符串中某个单词的 INDEX,如果可能还删除字符串中该单词之前的所有字符,这将使我的生活更轻松。

Could anyone help me? Im doing this on c#

有人可以帮助我吗?我在 c# 上做这个

采纳答案by Travis Sharp

You'll want to use the IndexOf function on a string. This will tell you the starting character position of the word, character, etc that you're looking for.

您需要在字符串上使用 IndexOf 函数。这将告诉您要查找的单词、字符等的起始字符位置。

Here is an example console app:

这是一个示例控制台应用程序:

    static void Main(string[] args)
    {
        String testing = "text that i am looking for";
        Console.Write(testing.IndexOf("looking") + Environment.NewLine);
        Console.WriteLine(testing.Substring(testing.IndexOf("looking")));

        Console.ReadKey();

    }

This will output:
15
looking for

这将输出:
15
寻找

回答by Sunil Dhappadhule

Yes, you can use Substring to delete all the characters previous

是的,您可以使用 Substring 删除之前的所有字符

string str = "I'm stuck here please help, something else....yyyy";
string output = str.Substring(str.IndexOf("help"));
WriteLine($"Output string value  :{output}");//help,something else....yyyy