开发者

Parsing a string and finding specific text in C#

开发者 https://www.devze.com 2023-02-12 03:31 出处:网络
I have a string which contains, lets say word \"key\" 5 times. Each time I see the word \"key\" in that string I want to print some text. How can I parse that string, find all \"key\" words and print

I have a string which contains, lets say word "key" 5 times. Each time I see the word "key" in that string I want to print some text. How can I parse that string, find all "key" words and print the texts accordingly? 5 words "key" - 5 printed texts. Th开发者_运维知识库is needs to be done in C#.

Thanks in advance.


How about using Regex.Matches:

string input = ...
string toPrint = ...

foreach (Match m in Regex.Matches(input, "key"))
    Console.WriteLine(toPrint);

EDIT: If by "word", you mean 'whole words', you need a different regex, such as:

@"\bkey\b"


Inside a loop, you can use the substring() method which offers the starting position parameter, and with each iteration you would advance the starting position; loop exits when you reach the string-not-found condition. EDIT: as for printing the text, that would depend on where you want to print it. EDIT2: You also need to consider whether the target string can appear in a manner you would not consider a true "hit":

          The key to success, the master key, is getting off your keyster...


I have an extension method I use for strings to get Indexes of a substring since .Net only provides IndexOf (single result for first substring match).

public static class Extensions
{
    public static int[] IndexesOf(this string str, string sub)
    {
        int[] result = new int[0];

        for(int i=0; i < str.Length; ++i)
        {
            if(i + sub.Length > str.Length)
                break;
            if(str.Substring(i,sub.Length).Equals(sub))
            {
                Array.Resize(ref result, result.Length + 1);
                result[result.Length - 1] = i;
            }
        }
        return result;
    }
}

You could use the extension method for all instances of key to print something

int[] indexes = stringWithKeys.IndexesOf("key");

foreach(int index in indexes)
{
    // print something
}

I know my code example may be longest but the extension method is reusable and you could place it in a "utility" type library for later use.


If it is a multiple word string, you could use LINQ.

string texttosearch;
string texttofind;

string[] source = texttosearch.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' },    StringSplitOptions.RemoveEmptyEntries);
 var matchQuery = from word in source
                     where word.ToLowerInvariant() == texttofind.ToLowerInvariant()
                     select word;

    foreach (string s in matchquery)
       console.writeline(whatever you want to print);
0

精彩评论

暂无评论...
验证码 换一张
取 消