Hi guys, so I need to add a 'space' between each character in my displayed text box.
I am giving the user a masked word like this He__o for him to guess and I want to convert this to H e _ _ o
I am using the following code to randomly replace characters with '_'
char[] partialWord = word.ToCharArray();
int numberOfCharsToHide = word.Length / 2; //divide word length by 2 to get chars to hide
Random randomNumberGenerator = new Random(); //generate rand number
HashSet<int> maskedIndices = new HashSet<int>(); //This is to make sure that I select unique indices to hide. Hashset helps in achieving this
for (int i = 0; i < numberOfCharsToHide; i++) //counter until it reaches words to hide
{
int rIndex = randomNumberGenerator.Next(0, word.Length); //init rindex
while (!maskedIndices.Add(rIndex))
{
rIndex = randomNumberGenerator.Next(0, word.Length); //This is to make sure that I select unique indices to hide. Hashset helps in achieving this
}
partialWord[rIndex] = '_'; //replace with _
}
return new string(partialWord);
I have tried : partialWord[rIndex] = '_ ';however this brings the error "Too many characters in literal"
I have tried : partialWord[rIndex] = "_ "; however this returns the error " Cannot convert type string to char.
Any idea how I can proceed to achieve a space between each character?
Thanks
The following code should do as you ask. I think the code is pretty self explanatory., but feel free to ask if anything is unclear as to the why or how of the code.
// char[] partialWord is used from question code
char[] result = new char[(partialWord.Length * 2) - 1];
for(int i = 0; i < result.Length; i++)
{
result[i] = i % 2 == 0 ? partialWord[i / 2] : ' ';
}
return new string(result);
Since the resulting string is longer than the original string, you can't use only one char array because its length is constant.
Here's a solution with StringBuilder:
var builder = new StringBuilder(word);
for (int i = 0 ; i < word.Length ; i++) {
builder.Insert(i * 2, " ");
}
return builder.ToString().TrimStart(' '); // TrimStart is called here to remove the leading whitespace. If you want to keep it, delete the call.
Related
I want to include two text box texts to one text box like this
both of them are multiline.
But I want special form of include, in other words I want to include them like this
textbox 1 texts: '' help''' '' other''
textbox 2 texts:' 1' '2' '' 3''
results: help1 _ help2 _ help3
other1_other2_other3
Multiline textboxes return a string array with the lines in the Lines property. You could do something like this
string[] words = textBox1.Lines;
string[] numbers = textBox2.Lines;
var resultLines = new string[words.Length];
var sb = new StringBuilder();
for (int i = 0; i < words.Length; i++) {
sb.Length = 0; // Reset StringBuilder for the next line.
for (int j = 0; j < numbers.Length; j++) {
sb.Append(words[i]).Append("-").Append(numbers[j]).Append("_");
}
if (sb.Length > 0) {
sb.Length--; // remove the last "_"
}
resultLines[i] = sb.ToString();
}
resultsTextBox.Lines = resultLines;
First we get the words and numbers arrays. Then we create a new array for the result. Since we want a result line for each word, we make it words.Length in size.
Then we loop through the words. We use a StringBuilder to build our new lines. This is more efficient as concatenation strings with +, as it minimizes copy operations and memory allocations.
In a nested loop we put the words and numbers together.
An elegant way to solve your issue is to make use of the String.Join method in C#. I'm adding this answer because I'm a big fan of the method and think it must be part of some answer to this question because it has to do with combining strings.
Here's the code that I'd use to solve the challenge:
string[] firstInput = textBox1.Lines;
string[] secondInput = textBox2.Lines;
var combinedInputs = new string[firstInput.Length];
var combinedLine = new string[secondInput.Length];
for(int i = 0; i < firstInput.Length; i++)
{
for(int j = 0; j < secondInput.Length; j++)
{
combinedLine[j] = firstInput[i] + secondInput[j];
}
//Combine all values of combinedLine with a '-' in between and add this to combinedInputs.
combinedInputs[i] = String.Join("-", combinedLine);
}
outputTextBox.Lines = combinedInputs; //the resulting output
I hope this answer helped aswell. And I'd like to give credits to Olivier for explaining the textbox part. Another thing that I'd like to add is that this answer isn't meant to be the most efficient, but is meant to be easy to read and understand.
I have a bot for my discord that I am adding a command to post one of those spongebob memes that you may have seen on twitter recently. I basically have to convert a string that the user enters, for example This is the string they would enter and it would convert it to something like this THis iS ThE sTRinG thEy WOulD EnTEr
I need to basically randomly set each character in that string to and uppercase or a lowercase.
Here is what I have so for, it prints out the original string and not the converted one.
commands.CreateCommand("spongememe").Parameter("message", ParameterType.Multiple).Do(async (e) =>
{
string message = "";
for (int i = 0; i < e.Args.Length; i++)
{
message += e.Args[i].ToString() + " ";
}
char[] array = message.ToCharArray();
for(int i = 0; i < array.Length; i++)
{
if (rnd.Next(0, 2) == 1)
Char.ToUpper(array[i]);
else
{
Char.ToLower(array[i]);
}
}
string newMessage = String.Join("", array);
await e.Channel.SendMessage(newMessage);
});
Any help on how to randomly select which characters are set to upper and lower case would be appreciated.
Here is how to randomly uppercase letters from a sentence:
var someString = "This is the string they would enter";
var randomizer = new Random();
var final =
someString.Select(x => randomizer.Next() % 2 == 0 ?
(char.IsUpper(x) ? x.ToString().ToLower().First() : x.ToString().ToUpper().First()) : x);
var randomUpperLower = new string(final.ToArray());
Console.WriteLine(randomUpperLower);
<== Try Me ==>
Char.ToUpper(char c); and Char.ToLower(char c); takes the char argument, transforms it either to uppercase or lowercase, and returns the transformed result. It doesn't change the char itself (see "Value and Reference Types" https://msdn.microsoft.com/en-us/library/4d43ts61(v=vs.90).aspx).
You need to modify it to something like this: array[i] = Char.ToUpper(array[i]);
I am trying to code a simple game where my program randomly selects a word from a dictionary and stores it in a text box/or label? (Not Sure of this part). Then I have another text box where the user enters his guess.
Now I want to give the user some hint.F or example the word:
'game' would look like '_ a m _' or 'g _ _ e'. I have no preference to how the characters are placed.
I have programmed all of the previous code including the random file handling method, all timers and counter etc. I am just stuck on this part.
The program undergoes the following code :
var lines = File.ReadAllLines(#"LOCATION");
textBox3.Text = lines[new Random().Next(lines.Length)];
to select a random word from the file. However the whole word is being shown in textbox 3 and not parts of it like i wish. I am at a complete loss for ideas on how to proceed. I could not find anything similar on the web.
Cheers,
R
Once you pick a random word from file, based on length of the word, decide on how many characters you'd want to hide and then randomly replace those many characters.
something like this-
public string GetPartialWord(string word)
{
if(string.IsNullOrEmpty(word))
{
return string.Empty;
}
char[] partialWord = word.ToCharArray();
int numberOfCharsToHide = word.Length / 2;
Random randomNumberGenerator = new Random();
HashSet<int> maskedIndices = new HashSet<int>();
for(int i=0;i<numberOfCharsToHide;i++)
{
int rIndex = randomNumberGenerator.Next(0, word.Length);
while(!maskedIndices.Add(rIndex))
{
rIndex = randomNumberGenerator.Next(0, word.Length);
}
partialWord[rIndex] = '_';
}
return new string(partialWord);
}
The code below will replace at least half of the characters with underscores. The code takes a word and keeps generating random numbers until it has replaced at least half of the characters with underscores.
public string ConvertToGuessWord(string word)
{
var guessWord = word;
int lastRandom = 0;
do
{
Random rand = new Random();
int thisRandom = 0;
do
{
thisRandom = rand.Next(0, guessWord.Length);
} while (lastRandom == thisRandom);
guessWord = guessWord.Replace(guessWord[thisRandom], '_');
lastRandom = thisRandom;
} while (guessWord.Count(x => x == '_') < (word.Length / 2));
return guessWord;
}
For the practice mostly.
This is the code in VB :
Private Function ScrambleWord(ByVal word As String) As String
Dim i As Integer = 0
Dim builder As System.Text.StringBuilder = New System.Text.StringBuilder()
Dim random As Random = New Random()
Dim index As Integer = 0
Dim lower As Integer = 0
Dim upper As Integer = 0
Dim parts() As Char
Dim part As Char
If Not (String.IsNullOrEmpty(word)) Then
If (word.Length > 3) Then
parts = word.ToCharArray()
builder.Append(word.Substring(0, 1))
parts = word.Substring(1, word.Length - 2).ToCharArray()
lower = LBound(parts) : upper = UBound(parts)
For i = lower To upper
index = random.Next(lower, upper)
part = parts(index)
parts(index) = parts(i)
parts(i) = part
Next
builder.Append(parts)
builder.Append(word.Substring(word.Length - 1, 1))
Return builder.ToString()
Else
Return word
End If
Else
Return String.Empty
End If
End Function
I used an online translation site and ended with this:
private string ScrambleWord(string word)
{
int i = 0;
StringBuilder builder = new StringBuilder();
Random random = new Random();
int index = 0;
int lower = 0;
int upper = 0;
char[] parts = null;
char part = '\0';
if (!(string.IsNullOrEmpty(word)))
{
if ((word.Length > 3))
{
parts = word.ToCharArray();
builder.Append(word.Substring(0, 1));
parts = word.Substring(1, word.Length - 2).ToCharArray();
lower = Information.LBound(parts);
upper = Information.UBound(parts);
for (i = lower; i <= upper; i++)
{
index = random.Next(lower, upper);
part = parts[index];
parts[index] = parts[i];
parts[i] = part;
}
builder.Append(parts);
builder.Append(word.Substring(word.Length - 1, 1));
return builder.ToString();
}
else
{
return word;
}
}
else
{
return string.Empty;
}
}
Im not sure if all the translation is good but now im getting two errors since Information not exist in c#
The errors are on the C# code on the lines:
lower = Information.LBound(parts);
upper = Information.UBound(parts);
Both errors are the same:
The name 'Information' does not exist in the current context
I took the VB code from this link and tried to convert it to c#
The Information class
comes from the Microsoft.VisualBasic namespace.
You can add a reference to Microsoft.VisualBasic and add using Microsoft.VisualBasic to the top of your file.
You don't in fact have anything named Information in the current context. (There's nothing declared in the code you posted, either in VB or C#.)
You don't need it anyway. It's being used to access the bounds of the parts array, and you know them already. You used them to create the array in the first place. (And you don't need the VisualBasic namespace.)
parts = word.Substring(1, word.Length - 2).ToCharArray();
lower = 0;
upper = parts.Length; // Note this is one higher than the last index,
// because the first index is zero
for (i = lower; i < upper; i++) // So use < rather than <= here
{
// Other code here.
}
LBounds and UBounds were needed in VB because arrays didn't always have to start at a certain index, as #competent_tech mentions in the comments. It was possible to declare an array with different indexes, even negative ones (eg., Dim parts(-3 To 3)). Also, everything in VB was a variant, so an array could be any type or be multi-dimensional, and the compiler couldn't always tell them apart. (For instance, retrieving cells from Excel in a Range - the result can be one cell, an entire row, or a rectangular or square block of cells.) There's no need for them here, because you know parts is simply a one dimensional character array. Arrays in C# start at index zero, and there's a method to retrieve the length of the array. The last index into the array is one less than that length, as my code above indicates with comments.
Change you code:
instead of
lower = Information.LBound(parts);
upper = Information.UBound(parts);
put
lower = parts.GetLowerBound(0);
upper = parts.GetUpperBound(0);
Information class is specific to VB; when writing C# code
you have to use an equivalent:
Information.LBound(value) == value.GetLowerBound(0);
Information.UBound(value) == value.GetUpperBound(0);
This is what I came up with:
private static string ScrambleWord(string word)
{
// easy exits come first
if (string.IsNullOrEmpty(word))
return String.Empty;
if (word.Length <= 3)
return word;
// now do the work
StringBuilder builder = new StringBuilder();
Random rand = new Random();
builder.Append(word.Substring(0, 1));
List<Char> parts = word.Substring(1).ToList();
while (parts.Count() > 0)
{
int upper = parts.Count();
int index = rand.Next(0, upper);
builder.Append(parts[index]);
parts.RemoveAt(index);
}
return builder.ToString();
}
Someone who is conversant in C# might point out mistakes.
How do I convert a word into a character array?
Lets say i have the word "Pneumonoultramicroscopicsilicovolcanoconiosis" yes this is a word ! I would like to take this word and assign a numerical value to it.
a = 1
b = 2
... z = 26
int alpha = 1;
int Bravo = 2;
basic code
if (testvalue == "a")
{
Debug.WriteLine("TRUE A was found in the string"); // true
FinalNumber = Alpha + FinalNumber;
Debug.WriteLine(FinalNumber);
}
if (testvalue == "b")
{
Debug.WriteLine("TRUE B was found in the string"); // true
FinalNumber = Bravo + FinalNumber;
Debug.WriteLine(FinalNumber);
}
My question is how do i get the the word "Pneumonoultramicroscopicsilicovolcanoconiosis" into a char string so that I can loop the letters one by one ?
thanks in advance
what about
char[] myArray = myString.ToCharArray();
But you don't actually need to do this if you want to iterate the string. You can simply do
for( int i = 0; i < myString.Length; i++ ){
if( myString[i] ... ){
//do what you want here
}
}
This works since the string class implements it's own indexer.
string word = "Pneumonoultramicroscopicsilicovolcanoconiosis";
char[] characters = word.ToCharArray();
Voilá!
you can use simple for loop.
string word = "Pneumonoultramicroscopicsilicovolcanoconiosis";
int wordCount = word.Length;
for(int wordIndex=0;wordIndex<wordCount; wordIndex++)
{
char c = word[wordIndex];
// your code
}
You can use the Linq Aggregate function to do this:
"wordsto".ToLower().Aggregate(0, (running, c) => running + c - 97);
(This particular example assumes you want to treat upper- and lower-case identically.)
The subtraction of 97 translates the ASCII value of the letters such that 'a' is zero. (Obviously subtract 96 if you want 'a' to be 1.)
you can use ToCharArray() method of string class
string strWord = "Pneumonoultramicroscopicsilicovolcanoconiosis";
char[] characters = strWord.ToCharArray();