简体   繁体   中英

C#: Matching exact word from a string

I have a string which contains key value pairs like "this:1 is:2 a:3 Bigtest:4 and:5 i:6 want:7 to:8 pass:9 in:10 this:11 test:12 and:13 string:14 continues:15"

Now I want to extract the value of a tag (say test) from this string. I am not able to extract the value of the tag test which is 12 because the matching logic which I have written matches the tab Bigtest and gives output as 4.

I am new in C# so need some expert help on this one.

My logic: message is the string containing key values and attribute is name of tag (test)

public static string GetAttributeValueByName(string message, string attributeName)
{
    int startIndex = message.IndexOf(attributeName + ":");

    string attribute = message.Substring(startIndex + (attributeName + "=").Length);

int position = attribute.IndexOf(' ', 1);


   if (position != -1)
{
    string attributeValue = attribute.Substring(1, position - 1);
    return attributeValue;
}

return "";
}

Thanks in advance.

If you first split the string at the spaces:

var pairs = input.Split(" ");

You'll end up with an array like this:

this:1
is:2
a:3
Bigtest:4
and:5
i:6
want:7
to:8
pass:9
in:10
this:11
test:12
and:13
string:14
continues:15

You can then loop over each element of the array splitting on the colon and check to see if the first element of that pair matches your test word.

string output; foreach (var pair in pairs) { var result = pair.Split(":"); if (result[0] == testWord) { output = result[1]; break; } }

Obviously you'll need to put in error trapping and input validation.

Assuming that the string will always be in the format "findstring:findvalue", you can do something like the below:

private string GetValueFromString(string SearchString, string FindString)
{
    foreach (string Items in SearchString.split(' '))
    {
        string SubItems = Items.split(':');
        if (SubItems[0] == FindString)
        {
            return SubItems[1];
        }
    }
    return null;
}

string SearchString = "this:1 is:2 a:3 Bigtest:4 and:5 i:6 want:7 to:8 pass:9 in:10 this:11 test:12 and:13 string:14 continues:15";
Console.WriteLine(GetValueFromString(SearchString, "test"));

The above also assumes that the text that you are searching for isn't repeated. My routine returns the value as a string. If you want to convert to a different type, such as an integer, you'll need to invoke Convert.ToInt32() around the return value and change the data type of the function.

There are many ways around this:

  • Insert a space at the beginning of the string, then search for the word preceded by a space;
  • Use a regular expression that matches a word boundary before the word by using the \\b metacharacter in the expression;
  • Use the String.Split function to split the string into an array of strings, then look at the first word in each array element;
  • Perform your search more manually in a loop by:
    1. Starting the current location at the beginning of the string;
    2. finding the next colon in the string;
    3. checking the word from the current location to that colon (if it matches you're done);
    4. finding the next space in the string;
    5. move the current location to the character after that space;
    6. repeat from step 2 until you find the word or reach the end of the string.

try this one:

    string message = "this:1 is:2 a:3 Bigtest:4 and:5 i:6 want:7 to:8 pass:9 in:10 this:11 test:12 and:13 string:14 continues:15";
    string searchWord = "this";
    int foundWords = 0;
    string[] arg = message.Split(new char[] { ' ' });
    int count = message.Split(' ').Length;
    for (int i = 0; i < count; i++)
    {
        if (arg[i].Contains(searchWord))
        {
            int index = arg[i].IndexOf(":") + 1;
            Console.WriteLine(arg[i].Substring(index, arg[i].Length - index));
            foundWords++;
        }
    }
    Console.WriteLine("found words: {0}", foundWords);

Update:

//message that you want to search in..
            string message = "this:1 is:2 a:3 Bigtest:4 and:5 i:6 want:7 to:8 pass:9 in:10 this:11 test:12 and:13 string:14 continues:15";
        //read the word .
        Console.Write("Enter your word: ");
    string searchWord = Console.ReadLine();
        // Init integer variable to count how many (world) in (message)
    int foundWords = 0;
        //split message string at spaces
    string[] arg = message.Split(new char[] { ' ' });
        // get the length of the message items
    int count = message.Split(' ').Length;
        //loop through message items
    for (int i = 0; i < count; i++)
    {
        //check if first array item contains the desired word
        if (arg[i].Contains(searchWord))
        {
            //get the index of (:) mark
            int index = arg[i].IndexOf(":") + 1;
            //substring the string after the (:) word
            Console.WriteLine(arg[i].Substring(index, arg[i].Length - index));
            //increase the counter
            foundWords++;
        }
    }
    Console.WriteLine("found words: {0}", foundWords);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM