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);
}
This should work:
var original = "stack";
for (int i = 0; i < original.Length; i++)
Console.WriteLine(original.Insert(i, original[i].ToString()));
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..
Related
I'm trying to solve the problem, but I just can't find the answer.
It is required to read a names.txt file, consisting of 5 words. After that, needs to convert them into char and then put the left side of the matrix and the bottom (look picture down). Other empty spaces need to fill with symbol "+".
I've tried many variations, but it doesn't display correctly.
Please help!
String txtFromFile = File.ReadAllText(#"C:\Users\source\names.txt");
Console.WriteLine("Words from file:\n{0}", txtFromFile);
int rows = 10;
int column = 10;
char[,] charArray = new char[rows, column];
for (int a = 0; a < rows; a++)
{
for (int b = 0; b < column; b++)
{
charArray[a, b] = '+';
Console.Write(string.Format("{0} ", charArray[a, b]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
If you are inexperienced with Linq her is a solution without using it.
int rows = 10;
int column = 10;
int lineCount = 0; //pointer variable to be used when padding lines with +
string emptyLine = "";
emptyLine = emptyLine.PadRight(column, '+'); //create empty line string
string[] lines = File.ReadLines(#"C:\Users\source\names.txt").ToArray(); //read all lines and store in a string array variable
//add lines with only +
for (int row = 0; row < rows - lines.Length; row++)
{
Console.WriteLine(emptyLine);
}
//loop through all read lines and pad them
foreach (string line in lines)
{
lines[lineCount] = lines[lineCount].Replace(line, line.PadRight(column, '+')); //pad the line and replace it in the collection
Console.WriteLine(lines[lineCount]);
lineCount++;
}
This solution uses string instead of char[]. However, if you need to get the array you can simply find it in the read lines collection by
char[] charArray = lines[i].ToCharArray();
for an arbitrary index i in the read lines collection.
You can do it in one Line,
using System.Linq;
...
//Read all lines instead of reading all inputs in form of text.
//Note: Expecting all words should be are stored on different line.
string[] txtFromFile = File.ReadAllLines(#"C:\Users\source\names.txt");
var result = Enumerable.Range(0, 10) //Iterate for 10 lines
.Select(x => x < 5 // Check for line number
? new string('+', 10) //If line is from 0..4, then print ++++++++++
: txtFromFile[x-5].PadRight(10, '+') //else print word then pad it with ++
);
//Print the result
Console.WriteLine(string.Join(Environment.NewLine, result));
.NET Fiddle
output:
++++++++++
++++++++++
++++++++++
++++++++++
++++++++++
DOG+++++++
SHEEP+++++
CHIMPANZEE
BREAVER+++
LION++++++
My goal was to get a 3DES password and for that im missing the last 6 digits.
for (int i = 0; i <= 16777215; i++)
{
string hexValue = i.ToString("X").PadLeft(6, '0');
}
You could just get the maximum number in your set of hexadecimals which goes from [0,FFFFFF] in decimal the set goes from [0, 16777215]
for(int i = 0; i <= 16777215; i++) {
string hexValue = i.ToString("X");
// your logic goes here...
}
This should do it:
var allHexadecimals = Enumerable.Range(0, 0xFFFFFF + 1)
.Select(i => i.ToString("X").PadLeft(6, '0'));
You can actually convert directly to Hex from c#, check out this article:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/how-to-convert-between-hexadecimal-strings-and-numeric-types
e.g. for(int i = 0x0; i < 0xff;i+=0x01) {Console.WriteLine(iConsole.WriteLine(value.ToString("X"));}
This question already has answers here:
Finding longest word in string
(4 answers)
Closed 3 years ago.
I got an assignment to make a method to find the longest word in a string without split, distinct and foreach.
I was able to split the words and count the length but I am stuck on how can I actually compare and write them out.
static void Main(string[] args)
{
String s1 = "Alex has 2 hands.";
longestWord(s1);
Console.
}
static void longestWord(String s1)
{
char emp = ' ';
int count = 0;
char[] ee = s1.ToCharArray();
for (int i = 0; i < ee.Length; i++)
{
if (ee[i] == emp || ee[i] == '.')
{
count++;
Console.Write(" " + (count-1));
Console.WriteLine();
count = 0;
}
else
{
Console.Write(ee[i]);
count++;
}
}
}
The output right now looks like this:
Alex 4
has 3
2 1
hands 5
I am pretty sure I would be able to get only the longest number to show by comparing count before reset with temp int but how to write out the word with it.
Or if there is a easier way which probably is.
You are already on a good way. Instead of directly printing the words, store the length and position of the longest word and print it at the end. Like so:
static void longestWord(String s1)
{
char emp = ' ';
int longestLength = 0;
int longestStart = 0;
int currentStart = 0;
for (int i = 0; i < s1.Length; i++)
{
if (s1[i] == emp || s1[i] == '.')
{
// calculate the current word length
int currentLength = i - currentStart;
// test if this is longer than the currently longest
if(currentLength > longestLength)
{
longestLength = currentLength;
longestStart = currentStart;
}
// a new word starts at the next character
currentStart = i + 1;
}
}
// print the longest word
Console.WriteLine($"Longest word has length {longestLength}: \"{s1.Substring(longestStart, longestLength)}\"");
}
There is no need for the .ToCharArray(). You can access the string directly.
I will question whether you are actually supposed to treat "2" as a word and count it at all. Using regular expressions will allow you to approach the problem using a LINQ one-liner:
static void Main(string[] args)
{
String s1 = "Alex has 2 hands.";
var word = longestWord(s1);
Console.WriteLine(word);
//Console.ReadLine();
}
static string longestWord(string s1) {
return Regex.Matches(s1,"[A-Za-z]+") // find all sequences containing alphabetical characters, you can add numberas as well: [A-Za-z0-9]
.Cast<Match>() // cast results to Enumberable<Match> so we can apply LINQ to it
.OrderByDescending(m => m.Length) // luckily for us, Match comes with Length, so we just sort our results by it
.Select(m => m.Value) // instead of picking up everything, we only want the actual word
.First(); // since we ordered by descending - first item will be the longest word
}
You can store for every word the chars in new list of chars (list for dynamic length)
and if the new word is longer of the prev long word convert it to string.
If you have two word in same length it will take the first.
If you want the last change the "maxLength < count" to "maxLength <= count"
static string longestWord(String s1)
{
char emp = ' ';
int count = 0;
int maxLength = 0;
string maxWord = string.Empty;
List<char> newWord = new List<char>();
char[] ee = s1.ToCharArray();
for (int i = 0; i < ee.Length; i++)
{
if (ee[i] == emp || ee[i] == '.')
{
if (maxLength < count)
{
maxLength = count;
maxWord = new string(newWord.ToArray());
}
count = 0;
newWord = new List<char>();
}
else
{
newWord.Add(ee[i]);
count++;
}
}
return maxWord;
}
For a string that may have zero or more hyphens in it, I need to extract all the different possibilities with and without hyphens.
For example, the string "A-B" would result in "A-B" and "AB" (two possibilities).
The string "A-B-C" would result in "A-B-C", "AB-C", "A-BC" and "ABC" (four possibilities).
The string "A-B-C-D" would result in "A-B-C-D", "AB-C-D", "A-BC-D", "A-B-CD", "AB-CD", "ABC-D", "A-BCD" and "ABCD" (eight possibilities).
...etc, etc.
I've experimented with some nested loops but haven't been able to get anywhere near the desired result. I suspect I need something recursive unless there is some simple solution I am overlooking.
NB. This is to build a SQL query (shame that SQL Server does't have MySQL's REGEXP pattern matching).
Here is one attempt I was working on. This might work if I do this recursively.
string keyword = "A-B-C-D";
List<int> hyphens = new List<int>();
int pos = keyword.IndexOf('-');
while (pos != -1)
{
hyphens.Add(pos);
pos = keyword.IndexOf('-', pos + 1);
}
for (int i = 0; i < hyphens.Count(); i++)
{
string result = keyword.Substring(0, hyphens[i]) + keyword.Substring(hyphens[i] + 1);
Response.Write("<p>" + result);
}
A B C D are words of varying length.
Take a look at your sample cases. Have you noticed a pattern?
With 1 hyphen there are 2 possibilities.
With 2 hyphens there are 4 possibilities.
With 3 hyphens there are 8 possibilities.
The number of possibilities is 2n.
This is literally exponential growth, so if there are too many hyphens in the string, it will quickly become infeasible to print them all. (With just 30 hyphens there are over a billion combinations!)
That said, for smaller numbers of hyphens it might be interesting to generate a list. To do this, you can think of each hyphen as a bit in a binary number. If the bit is 1, the hyphen is present, otherwise it is not. So this suggests a fairly straightforward solution:
Split the original string on the hyphens
Let n = the number of hyphens
Count from 2n - 1 down to 0. Treat this counter as a bitmask.
For each count begin building a string starting with the first part.
Concatenate each of the remaining parts to the string in order, preceded by a hyphen only if the corresponding bit in the bitmask is set.
Add the resulting string to the output and continue until the counter is exhausted.
Translated to code we have:
public static IEnumerable<string> EnumerateHyphenatedStrings(string s)
{
string[] parts = s.Split('-');
int n = parts.Length - 1;
if (n > 30) throw new Exception("too many hyphens");
for (int m = (1 << n) - 1; m >= 0; m--)
{
StringBuilder sb = new StringBuilder(parts[0]);
for (int i = 1; i <= n; i++)
{
if ((m & (1 << (i - 1))) > 0) sb.Append('-');
sb.Append(parts[i]);
}
yield return sb.ToString();
}
}
Fiddle: https://dotnetfiddle.net/ne3N8f
You should be able to track each hyphen position, and basically say its either there or not there. Loop through all the combinations, and you got all your strings. I found the easiest way to track it was using a binary, since its easy to add those with Convert.ToInt32
I came up with this:
string keyword = "A-B-C-D";
string[] keywordSplit = keyword.Split('-');
int combinations = Convert.ToInt32(Math.Pow(2.0, keywordSplit.Length - 1.0));
List<string> results = new List<string>();
for (int j = 0; j < combinations; j++)
{
string result = "";
string hyphenAdded = Convert.ToString(j, 2).PadLeft(keywordSplit.Length - 1, '0');
// Generate string
for (int i = 0; i < keywordSplit.Length; i++)
{
result += keywordSplit[i] +
((i < keywordSplit.Length - 1) && (hyphenAdded[i].Equals('1')) ? "-" : "");
}
results.Add(result);
}
This works for me:
Func<IEnumerable<string>, IEnumerable<string>> expand = null;
expand = xs =>
{
if (xs != null && xs.Any())
{
var head = xs.First();
if (xs.Skip(1).Any())
{
return expand(xs.Skip(1)).SelectMany(tail => new []
{
head + tail,
head + "-" + tail
});
}
else
{
return new [] { head };
}
}
else
{
return Enumerable.Empty<string>();
}
};
var keyword = "A-B-C-D";
var parts = keyword.Split('-');
var results = expand(parts);
I get:
ABCD
A-BCD
AB-CD
A-B-CD
ABC-D
A-BC-D
AB-C-D
A-B-C-D
I've tested this code and it is working as specified in the question. I stored the strings in a List<string>.
string str = "AB-C-D-EF-G-HI";
string[] splitted = str.Split('-');
List<string> finalList = new List<string>();
string temp = "";
for (int i = 0; i < splitted.Length; i++)
{
temp += splitted[i];
}
finalList.Add(temp);
temp = "";
for (int diff = 0; diff < splitted.Length-1; diff++)
{
for (int start = 1, limit = start + diff; limit < splitted.Length; start++, limit++)
{
int i = 0;
while (i < start)
{
temp += splitted[i++];
}
while (i <= limit)
{
temp += "-";
temp += splitted[i++];
}
while (i < splitted.Length)
{
temp += splitted[i++];
}
finalList.Add(temp);
temp = "";
}
}
I'm not sure your question is entirely well defined (i.e. could you have something like A-BCD-EF-G-H?). For "fully" hyphenated strings (A-B-C-D-...-Z), something like this should do:
string toParse = "A-B-C-D";
char[] toParseChars = toPase.toCharArray();
string result = "";
string binary;
for(int i = 0; i < (int)Math.pow(2, toParse.Length/2); i++) { // Number of subsets of an n-elt set is 2^n
binary = Convert.ToString(i, 2);
while (binary.Length < toParse.Length/2) {
binary = "0" + binary;
}
char[] binChars = binary.ToCharArray();
for (int k = 0; k < binChars.Length; k++) {
result += toParseChars[k*2].ToString();
if (binChars[k] == '1') {
result += "-";
}
}
result += toParseChars[toParseChars.Length-1];
Console.WriteLine(result);
}
The idea here is that we want to create a binary word for each possible hyphen. So, if we have A-B-C-D (three hyphens), we create binary words 000, 001, 010, 011, 100, 101, 110, and 111. Note that if we have n hyphens, we need 2^n binary words.
Then each word maps to the output you desire by inserting the hyphen where we have a '1' in our word (000 -> ABCD, 001 -> ABC-D, 010 -> AB-CD, etc). I didn't test the code above, but this is at least one way to solve the problem for fully hyphenated words.
Disclaimer: I didn't actually test the code
This program prints all possibilities of a string input, for example, if input is abc', the output should be the combinations, this works but when im creating the arraylist it's printing out numbers instead of the string combinations, code:
string input = Console.ReadLine();
int sl = input.Length;
ArrayList arr = new ArrayList();
for (int three = 0; three < sl; three++) {
for (int two = 0; two < sl; two++) {
for (int one = 0; one < sl; one++) {
char onef = input[one];
char twof = input[two];
char threef = input[three];
arr.Add(threef + twof + onef);
Console.Write(threef);
Console.Write(twof);
Console.WriteLine(onef);
}
}
}
Console.WriteLine("The elements of the ArrayList are:");
foreach(object obj in arr) {
Console.WriteLine(obj);
}
the output of the arraylist is numbers and not the string chars, help!
Just change these three lines
From:
char onef = input[one];
char twof = input[two];
char threef = input[three];
To:
string onef = input[one].ToString();
string twof = input[two].ToString();
string threef = input[three].ToString();
Alternate: change one line:
arr.Add(string.Format("{0}{1}{2}", a, b, c));
char cannot be concatenated like string. The + is interpreted numerically.