Hier mal sieben Beispiele wie man in einem String nach einem bestimmten Zeichen suchen kann:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
String source = "/dies/ist/ein/pfad/";
int count;
count = source.Length - source.Replace("/", "").Length;
Console.WriteLine("Methode 1: " + count);
count = source.Count(f => f == '/');
Console.WriteLine("Methode 2: " + count);
count = source.Split('/').Length - 1;
Console.WriteLine("Methode 3: " + count);
count = 0;
foreach (char c in source)
if (c == '/') count++;
Console.WriteLine("Methode 4: " + count);
int n=0;
count = 0;
while ((n = source.IndexOf('/', n)) != -1)
{
n++;
count++;
}
Console.WriteLine("Methode 5: " + count);
String searchChar = "/";
count = (source.Length - source.Replace(searchChar, "").Length)
/ searchChar.Length;
Console.WriteLine("Methode 6: " + count);
count = new Regex("/").Matches(source).Count;
Console.WriteLine("Methode 7: " + count);
Console.ReadLine();
}
}
}
Wer bietet mehr?