This should work:
var original = "stack";
for (int i = 0; i < original.Length; i++)
Console.WriteLine(original.Insert(i, original[i].ToString()));
Question
I am trying to create a string that inserts a duplicate letter from the original into the modified. For example, the output of one run would be:
Original word:
stack
Output:
sstack, sttack, staack, stacck, stackk
Does that make sense? I have this so far, and I feel i am close, but I am suing the wrong method to reassemble the string. Any help would be appreciated:
// Use ToCharArray to convert string to array.
char[] array = originalWord.ToCharArray();
// Loop through array.
for (int i = 0; i < array.Length; i++)
{
// Get character from array.
char letter = array[i];
string result = array.ToString();
string result2 = string.Join("", result.Select(x => x + letter));
Console.Write(result2);
}
La solution
This should work:
var original = "stack";
for (int i = 0; i < original.Length; i++)
Console.WriteLine(original.Insert(i, original[i].ToString()));
Autres conseils
You can use String.Insert to insert a string at a given index into another string.
IEnumerable<string> strings = originalWord
.Select((c, idx) => originalWord.Insert(idx, c.ToString()));
Fixed :
string originalWord = "stack";
// Use ToCharArray to convert string to array.
char[] array = originalWord.ToCharArray();
// Loop through array.
for (int i = 0; i < array.Length; i++)
{
// Get character from array.
char letter = array[i];
string result = originalWord.Insert(i, letter.ToString(CultureInfo.InvariantCulture));
Console.WriteLine(result);
}
The Linq way :
IEnumerable<string> words = originalWord.Select((letter, i) => originalWord.Insert(i, letter.ToString(CultureInfo.InvariantCulture)));
You can use String.Insert()
method like;
string s = "stack";
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine (s.Insert(i, s[i].ToString()));
}
Here is a DEMO
.
Oh god, already aded 3 answers when I writing it. Damn..