Incrementing characters in a particular pattern in C# - c#

The program should take in a parameter N and print out N + 1 lines.
I have to output something like this.
This is the output which I must get at N = 5
A //Increment by 0
AB //Increment by 1
ACE //Increment by 2
ADGJ //Increment by 3
AEIMQ //Increment by 4
The algorithm uses N as the number of characters to skip in between each add. So at N=3, it's A skip 3 to D, skip 3 to G, skip three to J.
And when the program runs out of upper case characters(i.e. When N is too big), it should start with lower case characters and if it runs out of lower case then it should again start with upper case and so on.
I am a novice to programming. And I dont really know where to start. I've been working around the loops for a while and still have no clue what-so-ever.

Here's another approach using a Char[], modulo, StringBuilder and a for-loop which increments by n for efficiency:
readonly static Char[] letters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();
static String appendChars(int n)
{
int length = n + 1;
StringBuilder sBuilder = new StringBuilder("A", length);
for (int i = n; sBuilder.Length < length; i += n)
{
Char nextChar = letters[i % letters.Length];
sBuilder.Append(nextChar);
}
return sBuilder.ToString();
}
test your sample data:
int n = 5;
IEnumerable<String> allWords = Enumerable.Range(0, n).Select(i => appendChars(i));
Console.Write(string.Join(Environment.NewLine, allWords));
outputs:
A
AB
ACE
ADGJ
AEIMQ
Here's the demo: http://ideone.com/0sspY

Try This :
public string GetOutPut(int increment)
{
string alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string output = string.Empty;
for(int i=0; i<=increment; i++)
{
int index = i*increment;
if(index>alphabets.Length)
index = index % alphabets.Length;
output+= alphabets[index];
}
return output;
}

It's not clear how you get the number of lines that you want - because you said N+1 but your example gives only N lines.
The following can be used to generate each one of those individual lines, and the Algo method can be modified to generate n+1 lines by sticking the code in a while loop, decrementing n and len and using AppendLine on the StringBuilder:
char[] allowedChars = Enumerable.Range('A', 26).Concat(Enumerable.Range('a', 26))
.Select(i => (char)i).ToArray();
[TestMethod]
public void Test()
{
Assert.AreEqual("A", Algo(0, 1));
Assert.AreEqual("AB", Algo(1, 2));
Assert.AreEqual("ACE", Algo(2, 3));
Assert.AreEqual("ADGJ", Algo(3, 4));
Assert.AreEqual("AEIMQ", Algo(4, 5));
}
public string Algo(int n, int len)
{
StringBuilder sb = new StringBuilder();
int nextCharIndex = 0;
for (int f = 0; f < len; f++)
{
sb.Append(allowedChars[nextCharIndex]);
//the `%`, or mod, here wraps around the next character back to upper case
nextCharIndex = (nextCharIndex + n) % allowedChars.Length;
}
return sb.ToString();
}

Related

Getting number of possible anagrams from a generic string, need a fast solution

I am currently working on an assignment where I need to write a small program that will take a generic string and should output how many possible anagrams that could be generated from the string.
The string that is the input can be up to 100 chars long and could include both lowercase and uppercase, in this case both lowercase and uppercase are considered distinct. The output should only be how many possible combinations, so I don't need to output the actual anagrams.The maximum timelimit is 1 second per string.
I have tried a number of diffrent ways of doing this, but one conclusion is that this should be solvable using some type of mathemathical algorithm.
The latest code I have tried with is this:
static void Main(string[] args)
{
string line;
while ((line = Console.ReadLine()) != null)
{
var uniqueStringArr = removeDuplicates(line);
Console.WriteLine(countDistinctPermutations(new string(uniqueStringArr)));
}
}
private static char[] removeDuplicates(string line)
{
var list = line.ToList();
return list.Distinct().ToArray();
}
static int MAX_CHAR = 100;
// Utility function to find factorial of n.
static int factorial(int n)
{
int fact = 1;
for (int i = 2; i <= n; i++)
fact = fact * i;
return fact;
}
// Returns count of distinct permutations
// of str.
static int countDistinctPermutations(String str)
{
int length = str.Length;
int[] freq = new int[MAX_CHAR];
// finding frequency of all the lower case
// alphabet and storing them in array of
// integer
for (int i = 0; i < length; i++)
if (str[i] >= 'a')
freq[str[i] - 'a']++;
// finding factorial of number of appearances
// and multiplying them since they are
// repeating alphabets
int fact = 1;
for (int i = 0; i < MAX_CHAR; i++)
fact = fact * factorial(freq[i]);
// finding factorial of size of string and
// dividing it by factorial found after
// multiplying
return factorial(length) / fact;
}
The thing is that this code does not give the correct answer for all my testcases.
The following sample data was provided for me :
Input string | Number of possible anagrams
at | 2
ordeals | 5040
abcdefghijklmnopqrstuvwxyz | 403291461126605635584000000
abcdefghijklmabcdefghijklm | 49229914688306352000000
abcdABCDabcd | 29937600
My code fixes the first two examples, but I get completly diffrent numbers for the other 3.
Is there anyone who can help me with this problem because I am running out of ideas ?
/Andreas
static BigInteger Factorial(long x)
{
return x <= 1 ? 1 : x * Factorial(x-1);
}
private static BigInteger NumberOfDistinctPermutationOf(string str)
{
BigInteger dividend = Factorial(str.Length);
foreach (char chr in str)
{
dividend /= Factorial(str.Count(c => c == chr));
str = str.Replace(chr.ToString(), string.Empty);
}
return dividend;
}
Description:
BigInteger Struct: Represents an arbitrarily large signed integer.
Enumerable.Count Method: Returns a number that represents how many elements in the specified sequence satisfy a condition.
String.Replace(String, String) Method: Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
GetNumberOfDistinctPermutation Method: Divides factorial of the length of the string by factorial of the number of occurrences of the char and then removes all occurrences of the char, for each char in the string.
static void Main(string[] args)
{
string line;
while ((line = Console.ReadLine()) != null)
{
Console.WriteLine($"{line} -> {countDistinctPermutations(line)}");
}
}
static BigInteger factorial(int n)
{
double fact = 1;
for (int i = 2; i <= n; i++)
fact = fact * i;
return fact;
}
static BigInteger countDistinctPermutations(String str)
{
// get a collection of {letter,occurences}
var duplicates = Array.GroupBy(p => p).Select(x => new { x.Key, count = x.Count() }).Where(x => x.count > 1);
BigInteger result = factorial(str.Length);
// foreach letter where occurence > 1 divide total permutations by the permutations for the occurence value (occurrence!)
foreach (var d in duplicates)
{
result /= factorial(d.count);
}
return result;
}
I only write code for a week so it's not that pretty but it works 100%.
static void Main(string[] args)
{
string inputData = Console.ReadLine();
Console.WriteLine(Solution(inputData));
}
static char[] convert(string text) // converting string to char[]
{
char[] newString = new char[text.Length];
for (int i = 0; i < text.Length; i++)
{
newString[i] = text[i];
}
return newString;
}
static double CalculateFctorial(double number) // calc. factorial
{
double factorial = 1;
for (int i = 1; i <= number; i++)
factorial *= i;
return factorial;
}
static int CountOcc(string text, char zet) // counting occurrences
{
int count = 0;
for (int i = 0; i < text.Length; i++)
{
if (text[i] == zet)
{
count++;
}
}
return count;
}
static double Solution(string text) // the soluton, counting occurences of
// each char in string and each factorial
{
double net = 0;
double sol = 1;
char[] newText = convert(text);
for (int i = 0; i <= newText.Length; i++)
{
if (text.Length > 0)
{
net = CountOcc(text, newText[i]);
sol = sol * CalculateFctorial(net);
if (newText[i] == text[0])
{ text = text.Trim(text[0]); }
}
}
double solution = CalculateFctorial(newText.Length) / sol;
return solution;
}

How to split characters of string equally between buttons?

I have an array of string elements of various words. I need the characters of each word be split equally into the text component of 3 buttons. For example, the array could hold the elements "maybe", "his", "car". In each game one of these words will be pulled from the array and its characters divided into the 3 buttons. For example, button 1 will have "ma", button 2 will have "yb" and button 3 "e" (for the word maybe). I then hide the text element of one button for the user to drag and drop the correct missing letter(s) into the space. The purpose of the game is to help children learn to spell. Does anyone know how I could go about dividing the characters equally into the 3 buttons?
Here's a function that would split the word into the amount of segments you want. You can then iterate over that list to set each segment to a button.Text.
public List<string> SplitInSegments(string word, int segments)
{
int wordLength = word.Length;
// The remainder tells us how many segments will get an extra letter
int remainder = wordLength % segments;
// The base length of a segment
// This is a floor division, because we're dividing ints.
// So 5 / 3 = 1
int segmentLength = wordLength / segments;
var result = new List<string>();
int startIndex = 0;
for (int i = 0; i < segments; i++)
{
// This segment may get an extra letter, if its index is smaller then the remainder
int currentSegmentLength = segmentLength + (i < remainder ? 1 : 0);
string currentSegment = word.Substring(startIndex, currentSegmentLength);
// Set the startindex for the next segment.
startIndex += currentSegmentLength;
result.Add(currentSegment);
}
return result;
}
usage:
// returns ["ma", "yb", "e"]
var segments = SplitInSegments("maybe", 3);
Edit
I like the fact that this is for teaching children. So here comes.
Regarding your question on splitting the string based on specific letter sequences: After you've split the string using regex, you will have an array of strings. Then determine the amount of items in the splitted string and concatenate or split further based on the number of segments:
// sequences to split on first
static readonly string[] splitSequences = {
"el",
"ol",
"bo"
};
static readonly string regexDelimiters = string.Join('|', splitSequences.Select(s => "(" + s + ")"));
// Method to split on sequences
public static List<string> SplitOnSequences(string word)
{
return Regex.Split(word, regexDelimiters).Where(s => !string.IsNullOrEmpty(s)).ToList();
}
public static List<string> SplitInSegments(string word, int segments)
{
int wordLength = word.Length;
// The remainder tells us how many segments will get an extra letter
int remainder = wordLength % segments;
// The base length of a segment
// This is a floor division, because we're dividing ints.
// So 5 / 3 = 1
int segmentLength = wordLength / segments;
var result = new List<string>();
int startIndex = 0;
for (int i = 0; i < segments; i++)
{
// This segment may get an extra letter, if its index is smaller then the remainder
int currentSegmentLength = segmentLength + (i < remainder ? 1 : 0);
string currentSegment = word.Substring(startIndex, currentSegmentLength);
// Set the startindex for the next segment.
startIndex += currentSegmentLength;
result.Add(currentSegment);
}
return result;
}
// Splitword will now always return 3 segments
public static List<string> SplitWord(string word)
{
if (word == null)
{
throw new ArgumentNullException(nameof(word));
}
if (word.Length < 3)
{
throw new ArgumentException("Word must be at least 3 characters long", nameof(word));
}
var splitted = SplitOnSequences(word);
var result = new List<string>();
if (splitted.Count == 1)
{
// If the result is not splitted, just split it evenly.
result = SplitInSegments(word, 3);
}
else if (splitted.Count == 2)
{
// If we've got 2 segments, split the shortest segment again.
if (splitted[1].Length > splitted[0].Length
&& !splitSequences.Contains(splitted[1]))
{
result.Add(splitted[0]);
result.AddRange(SplitInSegments(splitted[1], 2));
}
else
{
result.AddRange(SplitInSegments(splitted[0], 2));
result.Add(splitted[1]);
}
}
else // splitted.Count >= 3
{
// 3 segments is good.
result = splitted;
// More than 3 segments, combine some together.
while (result.Count > 3)
{
// Find the shortest combination of two segments
int shortestComboCount = int.MaxValue;
int shortestComboIndex = 0;
for (int i = 0; i < result.Count - 1; i++)
{
int currentComboCount = result[i].Length + result[i + 1].Length;
if (currentComboCount < shortestComboCount)
{
shortestComboCount = currentComboCount;
shortestComboIndex = i;
}
}
// Combine the shortest segments and replace in the result.
string combo = result[shortestComboIndex] + result[shortestComboIndex + 1];
result.RemoveAt(shortestComboIndex + 1);
result[shortestComboIndex] = combo;
}
}
return result;
}
Now when you call the code:
// always returns three segments.
var splitted = SplitWord(word);
Here is another approach.
First make sure that the word can be divided by the desired segments (add a dummy space if necessary) , then use a Linq statement to get your parts and when adding the result trim away the dummy characters.
public static string[] SplitInSegments(string word, int segments)
{
while(word.Length % segments != 0) { word+=" ";}
var result = new List<string>();
for(int x=0; x < word.Count(); x += word.Length / segments)
result.Add((new string(word.Skip(x).Take(word.Length / segments).ToArray()).Trim()));
return result.ToArray();
}
You can split your string into a list and generate buttons based on your list. The logic for splitting the word into a string list would be something similar to this:
string test = "maybe";
List list = new List();
int i = 0, len = 2;
while(i <= test.Length)
{
int lastIndex = test.Length - 1;
list.Add(test.Substring(i, i + len > lastIndex? (i + len) - test.Length : len));
i += len;
}
HTH

How to get every other character in a string in c#

so I'm working on this problem: https://www.hackerrank.com/challenges/30-review-loop/problem (it's in C#)
and so far I'm just trying to break it down piece by piece, and so far I was able to get it to show every other character, but I'm not sure how to concatenate each letter into a new string.
My code for the problem is as follows I've commented out the two for loops, because I felt like there was a more elegant solution to this than what I had, but I didn't want to lose where I was in case another path proved to be more challenging.
using System;
using System.Collections.Generic;
using System.IO;
class Solution {
static void Main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
int inputQTY = Int32.Parse(Console.ReadLine());
string input = Console.ReadLine(); // The example gives us the first word to be Hacker then the next word Rank on the next line, so the outputs would be Hce akr, and Rn ak respectively.
int strLen = input.Length;
char[] inputCharArray = input.ToCharArray();
string output = "";
/*
for (int j = 0; j < inputQTY; j++){
for (int i = 0; i < strLen; i++) {
if (j % 2 == 0 && i % 2 == 0) {
Console.WriteLine(inputCharArray[i]);
output = new string (new char[] {inputCharArray[i]});
Console.WriteLine(output);
Console.WriteLine("This is i: {0}", i);
Console.WriteLine("This is j: {0}", j);
Console.WriteLine("--------------");
Console.WriteLine("");
}
else {
Console.WriteLine("This is the next j part hopefully: {0}", j);
}
}
}*/
}
}
Like I understand I need to first step through the word, grab every other letter, then step through the word again and grab the remaining letters, then concatenate those letters into words, and concatenate those words into a sentence, so j would be the loop giving me the two words where I is the loop getting the two words put together..... but I'm having a difficult time wrapping my head around where I'm going wrong here. On top of this, I feel like there's another approach entirely that I'm missing, using commands I may not even know about.
Anyhoo any help is appreciated, hopefully I won't be so green after this. Thanks!
Ok so I ended up solving it with the following code, thank you for all your help everyone!
I ended up solving it with the following code (in C#):
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
class Solution {
static void Main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution */
int count = Int32.Parse(Console.ReadLine());
for (int k = 0; k < count; k++) {
char[] word = Console.ReadLine().ToCharArray();
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
for (int i = 0; i < word.Length; i+=2) {
sb1.Append(word[i]);
}
for (int j = 1; j < word.Length; j+=2) {
sb2.Append(word[j]);
}
Console.WriteLine(sb1 + " " + sb2);
}
}
}
LINQ version, updated to fix index error:
output = $"{new string(s.Where((x,i) => i % 2 == 0).ToArray())} {new string(s.Where((x,i) => i % 2 != 0).ToArray())}";
To explain, you're grabbing every character whose index in the string is evenly divisible by 2 and printing it, then every character in the string whose index is not evenly divisible by 2 and printing it.
Update:
Since I was asked for further explanation. First, here's the full code that runs successfully in the HackerRank challenge:
using System;
using System.Collections.Generic;
using System.Linq;
class Solution
{
static void Main(String[] args)
{
List<string> tests = new List<string>();
var testCount = int.Parse(Console.ReadLine());
for (var i = 0; i < testCount; i++)
{
tests.Add(Console.ReadLine());
}
foreach (var s in tests)
{
Console.WriteLine($"{new string(s.Where((x, i) => i % 2 == 0).ToArray())} {new string(s.Where((x, i) => i % 2 != 0).ToArray())}");
}
}
}
Regarding what each section of the code does:
i % 2 == 0
This is a test to see if a number is evenly divisible by two, or an even number.
s.Where((x,i) => i % 2 == 0)
This says, for the array of characters that make up the string 's', return all characters (the result is an IEnumerable) where that character's index (location in the string) is an even number.
new string(s.Where((x,i) => i % 2 == 0).ToArray())
This says to take that IEnumerable of characters with even numbered indexes and return them to an Array of characters. Then, create a new string out of that array of characters.
For the odd numbers, it's the same, but you use != 0 in the mod.
I used this simple method of appending to two StringBuilder objects
var sb1 = new StringBuilder();
var sb2 = new StringBuilder();
int i = 0;
foreach (char c in input)
{
var sb = (i % 2 == 0 ? sb1 : sb2);
sb.Append(c);
i = i + 1;
}
output = sb1.ToString() + " " + sb2.ToString();
this is the long way..
int count = int.Parse(Console.ReadLine());
for(int k = 0; k < count; k++){
char[] inputChars = Console.ReadLine().ToCharArray();
char[] evenChars = new char[inputChars.Length % 2 == 0 ? inputChars.Length / 2 : (inputChars.Length + 1) / 2];
char[] oddChars = new char[inputChars.Length - evenChars.Length];
int evenIndex=0,oddIndex = 0;
for(int i = 0; i < inputChars.Length;i++)
if(i % 2 == 0)
evenChars[evenIndex++] = inputChars[i];
else
oddChars[oddIndex++] = inputChars[i];
Console.WriteLine(string.Format("{0} {1}",string.Concat(evenChars),string.Concat(oddChars)));
}
an alternative..
int count = int.Parse(Console.ReadLine());
for(int k = 0; k < count; k++){
string input = Console.ReadLine();
Enumerable.Range(0, input.Length)
.OrderBy(o => o % 2 != 0)
.Select(o => {
if(o == 1)
Console.Write(" ");
Console.Write(input[o]);
return input[o];
}).ToArray();
Console.Write("\n");
}

Sum of two really big numbers

My task is to add a very big number to another and print the result.
Here is my implementation, it should give 1000 as output but it writes 0000.
How it should work:
if the two number has equal length:
just /10 for the digit %10 for the remainder. If the length of the result is bigger than the original add the last remainder to the last element of the output array.
if the two number has different length:
sum the intersection part and add the remainder (in temp) to the relative complementl.
What is wrong?
static int[] SumOfBigNumbers(int[] firstNumber, int[] secondNumber)
{
int temp = 0;
int maxLength = (Math.Max(firstNumber.Length, secondNumber.Length));
int minLength = (Math.Min(firstNumber.Length, secondNumber.Length));
int[] output = new int[maxLength + 1];
//sum of equal part
for (int counter = 0; counter < minLength; counter++)
{
output[counter] = (firstNumber[counter] + secondNumber[counter] + temp) % 10;
temp = (firstNumber[counter] + secondNumber[counter] + temp) / 10;
}
//exceptions add the temp to the bigger array
if (temp!=0)
{
//if first array is bigger than the second
if (firstNumber.Length > secondNumber.Length)
{
for (int i = minLength; i < maxLength + 1; i++)
{
output[i] = (firstNumber[i] + temp) % 10;
temp = (firstNumber[i] + temp) / 10;
}
}
//if second array is bigger than the first
else if (firstNumber.Length < secondNumber.Length)
{
for (int i = minLength; i < maxLength + 1; i++)
{
output[i] = (secondNumber[i] + temp) % 10;
temp = (secondNumber[i] + temp) / 10;
}
}
//if two number has equal length but there is temp left
else
{
output[maxLength] = temp;
}
}
return output;
}
static void Main()
{
int[] firstArray = new int[3] { 0, 0, 5 };
int[] secondArray = new int[3] { 0, 0,5 };
int[] output = SumOfBigNumbers(firstArray, secondArray);
foreach (var i in output)
{
Console.WriteLine(output[i]);
}
}
Edit: better if I copy the task: Write a method that calculates the sum of two very long positive integer numbers. The numbers are represented as array digits and the last digit (the ones) is stored in the array at index 0. Make the method work for all numbers with length up to 10,000 digits.
While BigInteger is a better way to handle big numbers, I think your bug is in while printing the output. try this:
foreach (var i in output)
{
Console.WriteLine(i);
}
also this will print 0001, better reverse it while printing
Your code works fine but you have a small bug where you display the output array.
You do a foreach (var i in output) {, but you use the i as an index, which it isn't. It is already the actual value. Just write the i to the console.
foreach (var i in output)
{
Console.WriteLine(i);
}
// Output:
// 0
// 0
// 0
// 1
Or use a for loop to go through the array by index.
for (int i = 0; i < output.Length; i++)
{
Console.WriteLine(output[i]);
}
// Output:
// 0
// 0
// 0
// 1

More efficient way to get all indexes of a character in a string

Instead of looping through each character to see if it's the one you want then adding the index your on to a list like so:
var foundIndexes = new List<int>();
for (int i = 0; i < myStr.Length; i++)
{
if (myStr[i] == 'a')
foundIndexes.Add(i);
}
You can use String.IndexOf, see example below:
string s = "abcabcabcabcabc";
var foundIndexes = new List<int>();
long t1 = DateTime.Now.Ticks;
for (int i = s.IndexOf('a'); i > -1; i = s.IndexOf('a', i + 1))
{
// for loop end when i=-1 ('a' not found)
foundIndexes.Add(i);
}
long t2 = DateTime.Now.Ticks - t1; // read this value to see the run time
I use the following extension method to yield all results:
public static IEnumerable<int> AllIndexesOf(this string str, string searchstring)
{
int minIndex = str.IndexOf(searchstring);
while (minIndex != -1)
{
yield return minIndex;
minIndex = str.IndexOf(searchstring, minIndex + searchstring.Length);
}
}
usage:
IEnumerable<int> result = "foobar".AllIndexesOf("o"); // [1,2]
Side note to a edge case: This is a string approach which works for one or more characters. In case of "fooo".AllIndexesOf("oo") the result is just 1 https://dotnetfiddle.net/CPC7D2
How about
string xx = "The quick brown fox jumps over the lazy dog";
char search = 'f';
var result = xx.Select((b, i) => b.Equals(search) ? i : -1).Where(i => i != -1);
The raw iteration is always better & most optimized.
Unless it's a bit complex task, you never really need to seek for a better optimized solution...
So I would suggest to continue with :
var foundIndexes = new List<int>();
for (int i = 0; i < myStr.Length; i++)
if (myStr[i] == 'a') foundIndexes.Add(i);
If the string is short, it may be more efficient to search the string once and count up the number of times the character appears, then allocate an array of that size and search the string a second time, recording the indexes in the array. This will skip any list re-allocations.
What it comes down to is how long the string is and how many times the character appears. If the string is long and the character appears few times, searching it once and appending indicies to a List<int> will be faster. If the character appears many times, then searching the string twice (once to count, and once to fill an array) may be faster. Exactly where the tipping point is depends on many factors that can't be deduced from your question.
If you need to search the string for multiple different characters and get a list of indexes for those characters separately, it may be faster to search through the string once and build a Dictionary<char, List<int>> (or a List<List<int>> using character offsets from \0 as the indicies into the outer array).
Ultimately, you should benchmark your application to find bottlenecks. Often the code that we think will perform slowly is actually very fast, and we spend most of our time blocking on I/O or user input.
public static List<int> GetSubstringLocations(string text, string searchsequence)
{
try
{
List<int> foundIndexes = new List<int> { };
int i = 0;
while (i < text.Length)
{
int cindex = text.IndexOf(searchsequence, i);
if (cindex >= 0)
{
foundIndexes.Add(cindex);
i = cindex;
}
i++;
}
return foundIndexes;
}
catch (Exception ex) { }
return new List<int> { };
}
public static String[] Split(this string s,char c = '\t')
{
if (s == null) return null;
var a = new List<int>();
int i = s.IndexOf(c);
if (i < 0) return new string[] { s };
a.Add(i);
for (i = i+1; i < s.Length; i++) if (s[i] == c) a.Add(i);
var result = new string[a.Count +1];
int startIndex = 0;
result[0] = s.Remove(a[0]);
for(i=0;i<a.Count-1;i++)
{
result[i + 1] = s.Substring(a[i] + 1, a[i + 1] - a[i] - 1);
}
result[a.Count] = s.Substring(a[a.Count - 1] + 1);
return result;
}

Categories

Resources