Home > other >  How to find number of specific strings in a string in c#
How to find number of specific strings in a string in c#

Time:01-24

There is a string: xxoxoxoxoxoxooxxxxox where x is a seat that is occupied and o is not, I have to find individual occupied seats, with both sides having an x.

I tried to look at

for (int i = 0; i < string.Length; i  ) { 
    if(string[i]=='x' && string[i   1]=='o' && string[i   2] == 'x') 
      { 
        count  ; 
      } 
}

but i got error so I was wondering if theres a good way to do it.

CodePudding user response:

As the question is pretty unclear, I am assuming that you are looking for a pattern xox and want to know the position of o.

you can run a for loop and get the index.

to get the count of such patterns. you can increment the count by 1.

string str = "xxoxoxoxoxoxooxxxxox";

for(int i = 0; i < str.Length - 2; i  )
{
    if (str[i] == 'x' && str[i  1] == 'o' && str[i  2] == 'x')
    {
        Console.WriteLine(i   1);
        count  ; 
    }
}

you can change the character value based on your requirement.

CodePudding user response:

you can use enter image description here

CodePudding user response:

RegEx approach which gives you all indices of individual occupied seats oxo https://dotnetfiddle.net/3jc1Vq

string input = "xxoxoxoxoxoxooxxxxox";
//                ^ ^ ^ ^ ^       ^
int[] indices = Regex.Matches(input, "(?<=x)o(?=x)").Cast<Match>().Select(x => x.Index).ToArray();

// in case you only want the count
int count = Regex.Matches(input, "(?<=x)o(?=x)").Count(); 

CodePudding user response:

I made a working example that makes use of ReadOnlySpan<T> and avoids RegEx and over allocation.

using System;
using System.Collections.Generic;
                    
public class Program
{
    public static void Main()
    {
        string seats = "xxoxoxoxoxoxooxxxxox";
        var results = seats.ToCharArray().GetSingles('o');
        foreach(var i in results)
        {
            Console.WriteLine(i);
        }
    }
}
                                   
public static class Ext
{
    public static IReadOnlyList<int> GetSingles<T>(this T[] source, T search)
    {
        var results = new List<int>();
        if(source.Length == 0)
        {
            return results;
        }
        
        if (source.Length == 1)
        {
            if (source[0].Equals(search))
            {
                results.Add(0);
            }
            
            return results;
        }
        
        if(source.Length >= 2)
        {
            if (source[0].Equals(search) && ! source[1].Equals(search))
            {
                results.Add(0);
            }
            
            if (source.Length == 2)
            {
                if (!source[0].Equals(search) && source[1].Equals(search))
                {
                    results.Add(1);
                }
                
                return results;
            }
        }
        
        ReadOnlySpan<T> window = new ReadOnlySpan<T>(source, 0, 3);
        int i = 1;
        for(; i < source.Length - 1; i  )
        {
            window = new ReadOnlySpan<T>(source, i - 1, 3);
            if(!window[0].Equals(search) && 
                window[1].Equals(search) &&
               !window[2].Equals(search))
            {
                results.Add(i);
            }
        }
        
        if(!window[1].Equals(search) && window[2].Equals(search))
        {
            results.Add(i   1);
        }
        
        return results;
    }
}

This outputs,

2
4
6
8
10
18

With the more challenging test data,

public class Program
{
    public static void Main()
    {
        var tests = new string[]
        {
            "",
            "o",
            "x",
            "oo",
            "ox",
            "xo",
            "xx",
            "oxx",
            "oox",
            "xox",
            "xoo",
            "xoxoxoxo",
            "xoxoxoxoo",
            "xoxoxox"
        };
        
        for(var i = 0; i < tests.Length; i  )
        {
            string seats = tests[i];
            Console.WriteLine($"{i}:\"{seats}\"");
            var results = seats.ToCharArray().GetSingles('o');
            foreach(var r in results)
            {
                Console.WriteLine(r);
            }
        }
    }
}

we get the correct output,

0:""
1:"o"
0
2:"x"
3:"oo"
4:"ox"
0
5:"xo"
1
6:"xx"
7:"oxx"
0
8:"oox"
9:"xox"
1
10:"xoo"
11:"xoxoxoxo"
1
3
5
8
12:"xoxoxoxoo"
1
3
5
13:"xoxoxox"
1
3
5
  • Related