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();
Related
(not allowed to use LINQ or other libraries) I've created a While loop to convert each char into it opposite form of Uppercase or Lowercase and at the end of the loop I'm getting a 'System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'' and I've no idea how to resolve the error. The loop carries out as expected but faces this error when the last char in the array has been converted and retests the parameters of the 1st embedded while loop. Also if there's an easier way to do this I'm all ears. Thanks in advance
string text2 = "HELLO my friEND";
char[] convert = text2.ToCharArray();
int b = 0;
int a = convert.Length;
while (b <= a)
{
while (char.IsUpper(convert[b]))
{
char.ToLower(convert[b]);
b++;
}
while (char.IsLower(convert[b]))
{
char.ToLower(convert[b]);
b++;
}
while (char.IsWhiteSpace(convert[b]))
{
b++;
}
}
string hello = new string(convert);
Console.Write(hello);
Console.WriteLine();
Console.Write("test");
return 0;
while (b <= a) needs to be while (b < a). Indexes are zero-based, meaning the last index will be equal to length - 1.
You also increment b after every check (the b++ in each of the internal while loops) - once the last letter is converted it checks the condition in the while loop again, and after it converted the "D" b is now 15 - but the string is only length 14. You need to check for this in each of the internal while loops, something like
while (b < a && char.IsUpper(convert[b]))
Alternatively, rework this method entirely to avoid these kinds of problems in the first place (by e.g., using a for loop).
You had a lot of problems with your code, you weren't actually mutating the array by using the return result of the char methods, you had 2 ToLowers() and you were reading over the end of the array.
However, you can make it a little more succinct:
string text2 = "HELLO my friEND";
char[] convert = text2.ToCharArray();
for (int i = 0; i < convert.Length; i++)
if (char.IsWhiteSpace(convert[i]))
continue;
else if (char.IsUpper(convert[i]))
convert[i] = char.ToLower(convert[i]);
else
convert[i] = char.ToUpper(convert[i]);
Purely academic purposes, you could also use a switch here, though it's the wrong tool for the job:
for (int i = 0; i < convert.Length; i++)
convert[i] = convert[i] switch
{
_ when char.IsWhiteSpace(convert[i]) => convert[i],
_ when char.IsUpper(convert[i]) => char.ToLower(convert[i]),
_ when char.IsLower(convert[i]) => char.ToUpper(convert[i]),
_ => throw new ArgumentOutOfRangeException()
};
And as a bonus prize, here is a Linq variation:
string text2 = "HELLO my friEND";
static char Change(char c)
{
if (char.IsWhiteSpace(c)) return c;
return char.IsUpper(c) ? char.ToLower(c) : char.ToUpper(c);
}
Console.Write(string.Concat(text2.Select(Change)));
Please optimize your code like this:
while (b < a)
{
if (char.IsUpper(convert[b]))
{
convert[b] = char.ToLower(convert[b]);
}
else if (char.IsLower(convert[b]))
{
convert[b] = char.ToUpper(convert[b]);
}
b++;
}
So I want to be able to create a headline and underline it with for example an "=". However I want the number of "=" to match with the number of characters in the headline. Preferably I want to be able to do it with a for loop.
Here's what I have so far.
string headLine = "Example";
Console.WriteLine(headLine);
for (char i = '='; i <= headLine.Length; i += '=')
{
Console.WriteLine(i);
}
No need for any loops, just create a new string to your specifications:
string headLine = "Example";
Console.WriteLine(headLine);
Console.WriteLine(new string('=', headLine.Length));
your for loop is completely wrong, you are comparing a char which represents value with an int that represents length. Do something like this instead:
string headLine = "Example";
Console.WriteLine(headLine);
char c = '=';
for (int i=0; i < headLine.Length; i++) //from 0 to length-1 gives the full length
{
Console.Write(c);
}
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]);
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.
I'm trying to have a suggestion feature for the search function in my program eg I type janw doe in the search section and it will output NO MATCH - did you mean jane doe? I'm not sure what the problem is, maybe something to do with char/string comparison..I've tried comparing both variables as type char eg char temp -->temp.Contains ...etc but an error appears (char does not contain a definition for Contains). Would love any help on this! 8)
if (found == false)
{
Console.WriteLine("\n\nMATCH NOT FOUND");
int charMatch = 0, charCount = 0;
string[] checkArray = new string[26];
//construction site /////////////////////////////////////////////////////////////////////////////////////////////////////////////
for (int controlLoop = 0; controlLoop < contPeople.Length; controlLoop++)
{
foreach (char i in userContChange)
{
charCount = charCount + 1;
}
for (int i = 0; i < userContChange.Length; )
{
string temp = contPeople[controlLoop].name;
string check=Convert.ToString(userContChange[i]);
if (temp.Contains(check))
{
charMatch = charMatch + 1;
}
}
int half = charCount / 2;
if (charMatch >= half)
{
checkArray[controlLoop] = contPeople[controlLoop].name;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
Console.WriteLine("Did you mean: ");
for (int a = 0; a < checkArray.Length; a++)
{
Console.WriteLine(checkArray[a]);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
A string is made up of many characters. A character is a primitive, likewise, it doesn't "contain" any other items. A string is basically an array of characters.
For comparing string and characters:
char a = 'A';
String alan = "Alan";
Debug.Assert(alan[0] == a);
Or if you have a single digit string.. I suppose
char a = 'A';
String alan = "A";
Debug.Assert(alan == a.ToString());
All of these asserts are true
But, the main reason I wanted to comment on your question, is to suggest an alternative approach for suggesting "Did you mean?". There's an algorithm called Levenshtein Distance which calculates the "number of single character edits" required to convert one string to another. It can be used as a measure of how close two strings are. You may want to look into how this algorithm works because it could help you.
Here's an applet that I found which demonstrates: Approximate String Matching with k-differences
Also the wikipedia link Levenshtein distance
Char type cannot have .Contains() because is only 1 char value type.
In your case (if i understand), maybe you need to use .Equals() or the == operator.
Note: for compare String correctly, use .Equals(),
the == operator does not work good in this case because String is reference type.
Hope this help!
char type dosen't have the Contains() method, but you can use iit like this: 'a'.ToString().Contains(...)
if do not consider the performance, another simple way:
var input = "janw doe";
var people = new string[] { "abc", "123", "jane", "jane doe" };
var found = Array.BinarySearch<string>(people, input);//or use FirstOrDefault(), FindIndex, search engine...
if (found < 0)//not found
{
var i = input.ToArray();
var target = "";
//most similar
//target = people.OrderByDescending(p => p.ToArray().Intersect(i).Count()).FirstOrDefault();
//as you code:
foreach (var p in people)
{
var count = p.ToArray().Intersect(i).Count();
if (count > input.Length / 2)
{
target = p;
break;
}
}
if (!string.IsNullOrWhiteSpace(target))
{
Console.WriteLine(target);
}
}