Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Find longest span of characters in string
//Rextester.Program.Main is the entry point for your code. Don't change it. //Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Rextester { public class Program { public static void Main(string[] args) { string sample = RandomString(100); //Generates 100 random chars (see below), can change length or to whatever you want char lookFor = RandomIn(sample); //Picks a random char to look for, can change to any character Console.WriteLine("String: \"" + sample + "\""); int current = 0, max = 0; int index = -1, maxIndex = -1; //Start searching for (int at = 0; at < sample.Length; at++) { char c = sample[at]; if (c == lookFor) { if (current == 0) index = at; current++; if (current > max) { max = current; maxIndex = index; } } else current = 0; } //Print out result if (index == -1) Console.WriteLine("Could not find '" + lookFor + "'"); else { Console.Write("Found '" + lookFor + "' " + max + " times at most, starting at index " + maxIndex); if (sample.Length > 15) { Console.Write(", at \""); if (maxIndex - 3 < 0) Console.Write(sample.Substring(0, max + 3)); else if (maxIndex + max + 3 >= sample.Length) Console.Write(sample.Substring(maxIndex - 3, max)); else Console.Write(sample.Substring(maxIndex - 3, max + 6)); Console.Write("\""); } Console.WriteLine(); } //Console.ReadLine(); } static string RandomString(int len) { string chars = "!@#$%^&*()!!!!!!"; //Can change to whatever you want, repeating chars will increase chance of being picked string result = ""; Random rand = new Random(); while (result.Length < len) { int index = rand.Next(chars.Length); result += chars[index]; } return result; } static char RandomIn(string chars) { Random r = new Random(); return chars[r.Next(chars.Length)]; } } }
run
|
edit
|
history
|
help
0
MostFrequent
Fibonacci Series
xyz
code exple
form
Interface referance variable
ConcurrentQueue<T>
Ftg
Public access specifier
1