I am trying to code a simple app to let a user type a letter, and find out which position it is in in an Array, and than replace that position with the letter k.
I don`t know how to replace a char at a specific position, and the program give strange value of -1.
Thanks for any help.
Source code:
class Program
{
static void Main(string[] args) {
Random r = new Random();
string[] d = {"a" , "b" , "c" , "d" };
string randomString= "";
for (int i= 0; i < 5; i++)
{
randomString = randomString + d[r.Next(d.Length)];
}
Console.WriteLine("Debug: Random string output: " + randomString);
char[] charArray = randomString.ToCharArray();
Console.WriteLine("Type one char of random String to find postion of it:");
string userinput = Console.ReadLine();
int pos = Array.IndexOf(charArray , userinput);
Console.WriteLine(userinput +" is at " + pos + ".");
//Something to replace a char at that position with k
// Here display modified string with "k"
Console.WriteLine(randomString);
Console.ReadLine();
/*
* Console output:
Debug: Random string output: bbccb
Type one char of random String to find postion of it:
c is at -1
*/
}
}
The problem is in this line
int pos = Array.IndexOf(charArray , userinput);
You have an array of chars but you are searching a string
Change it to
int pos = Array.IndexOf(charArray , userinput[0]);
Of course you should also check if the user types anything
Your value userinput is a string, and hence a mismatch when compared to any single character in your array. You could get the first item in the string using userinput[0], but if a user enters an empty string, then that will crash (an empty string has no valid "position 0").
Instead, try this:
int pos = Array.IndexOf(charArray , userinput.FirstOrDefault());
That will return the first character if there is any; if not, it will return a char with a value of 00, which will not match anything in your array, but also not cause the program to crash.
Oh, and one more thing: To replace a character at a specific position, just set the value for that position directly:
charArray[pos] = 'K'; // Will replace character at position pos.
Related
My apologies if I didn't explain it clear the first time. I have edited my explanation further in bold below.
In the program below user enters a word and then enters a letter which the user would like to replace with any character. For instance, user enter's a word "Hello" and the replacement letter is "l" with "$". So "Hello" will become "He$$o". First, the goal is to find the location of "l" (example - 2,3) and then replace the element in that specific location.
I started by finding the location of "l" and storing it in a findIndex array. Every time I run the program I get "22222" stored in findIndex[] array. At this point, I am not even sure if I am even applying the right logic. Any advice will be appreciated! Please don't use LINQ.
public static void RemoveSpecifiedCharacters()
{
Console.WriteLine("\nWrite a word/sentence: ");
string myString = Console.ReadLine();
Console.Write("Type the character you would like to replace: ");
string myCharacter = Console.ReadLine();
int[] findIndex = new int[myString.Length];
for (int i = 0; i < myString.Length; i++)
{
findIndex[i] = myString.IndexOf(myCharacter, 0);
}
for (int i = 0; i < findIndex.Length; i++)
{
Console.Write(findIndex[i]);
}
}
This is probably what you want :
public static void RemoveSpecifiedCharacters()
{
Console.WriteLine("\nWrite a word/sentence: ");
string myString = Console.ReadLine();
Console.Write("Type the character you would like to replace: ");
string myCharacter = Console.ReadLine();
List<int> findIndex = new List<int>();
int offs = 0;
while (offs < myString.Length)
{
offs = myString.IndexOf(myCharacter, offs);;
if (offs == -1)
break;
findIndex.Add(offs);
offs++;
}
for (int i = 0; i < findIndex.Count; i++)
{
Console.Write(findIndex[i]);
}
}
Set an initial offset to the start of the string, try to find index of required character if not found exit, otherwise store the location & increment the offset so the next loop starts after the found position. Then keep looping.
As you do not know how many characters will be found, then a list is better than an array to store the results. It can always be converted to an array with .ToArray() afterwards.
Below should serve the purpose :
var str = "Hello";
var replaced = str.Replace('l', '$');
Even though it's easier to use String.Replace, I just want to give you an explanation why you are getting [2,2,2,2,2] array.
Firstly, IndexOf method returns index of character's first occurence, starting from 0.
Secondly, you are using method overload IndexOf(myCharacter, 0) which "says" that character search should be done always from the start of the string.
To circumvent the issue, you should use IndexOf(myCharacter, i, 1) instead to set the search to start from i-th character, not the start of string.
I guess a simple solution would be to split the string into a character array and then do the comparison?
For example something like:
Console.WriteLine("\nWrite a word/sentence: ");
char[] myString = Console.ReadLine().ToCharArray();
Console.Write("Type the character you would like to replace: ");
char myCharacter = Console.ReadLine().ToCharArray()[0];
int[] findIndex = new int[myString.Length];
int indexCount = 0;
for (int i = 0; i < myString.Length; i++)
{
if (myString[i] == myCharacter)
findIndex[indexCount++] = i;
}
for (int i = 0; i < indexCount; i++)
{
Console.Write(findIndex[i]);
}
How do I convert alphabet letter from textBox to an integer?
For example, if the user inputs "B" in the textBox, I am trying to convert B to the number 1
string a = textBox1.Text
int number = 1;
number = int.Parsed (a);
messageBox.Show(number.ToString());
Your first task is to capture only the first character from the input:
string str = textBox1.Text;
char chr = str[0]; // get first character
Now the character can be directly converted to an integer, for example:
int number = (int)chr;
However, the character 'A' is actually represented by the number 65, 'B' 66, and so on (see ASCII), so you'll have to subtract that from your input to get the intended value:
int value = number - 65;
Or if you prefer:
int value = number - (int)'A';
Now you might want to normalize input so a character 'a' will be treated as 'A', so in the end it would look a bit like this:
string str = textBox1.Text.ToUpperCase();
char chr = str[0];
int number = (int)chr;
int value = number - 65;
MessageBox.Show(value.ToString());
The following simple program will find the last letter in a string that a user enters and then remove everything after that point. So, if a person enters one string.... everything after the g should be removed. I've got the following as a little program:
class Program
{
static void Main(string[] args)
{
Console.Write("Enter in the value of the string: ");
List<char> charList = Console.ReadLine().Trim().ToList();
int x = charList.LastIndexOf(charList.Last(char.IsLetter)) ;
Console.WriteLine("this is the last letter {0}", x);
Console.WriteLine("This is the length of the string {0}", charList.Count);
Console.WriteLine("We should have the last {0} characters removed", charList.Count - x);
for (int i = x; i < charList.Count; i++)
{
charList.Remove(charList[i]);
}
foreach (char c in charList)
{
Console.Write(c);
}
Console.ReadLine();
}
}
I've tried numerous variations of this and none of them getting it exactly write. This particular program with an input of string.... the output of the program is strin.. So somehow it's leaving on what it should be taking away and it's actually taking away letters that it shouldn't. Can anyone give an indication as to why this is happening? The desired output, again should be string.
Try this:
string input = Console.ReadLine(); // ABC.ABC.
int index = input.Select((c, i) => new { c, i })
.Where(x => char.IsLetter(x.c))
.Max(x => x.i);
string trimmedInput = input.Substring(0, index + 1);
Console.WriteLine(trimmedInput); // ABC.ABC
Jsut for the explanation, that's because each time you remove a character, you increment the i counter but also decrementing charList.Count so you're actually removing 1 character, leaving the next one, then removing again and so on...
For example, with the input "string...." and x being 5 (index of the G letter) you're doing :
1st iteration :
Remove the g char so x becomes 6 and charList.Count becomes 9 (10-1)
Next iteration :
Remove the char at index 6 which is now the second . (your string being "strin....").
So you missed the first point.
I let you check other answers as they contains more elegant solutions for your problems.
I think it would be a lot more straight forward to simply Substring the string the user entered. So consider the following modified code:
class Program
{
static void Main(string[] args)
{
Console.Write("Enter in the value of the string: ");
var s = Console.ReadLine().Trim();
List<char> charList = s.ToList();
int x = charList.LastIndexOf(charList.Last(char.IsLetter)) ;
Console.WriteLine("this is the last letter {0}", x);
Console.WriteLine("This is the length of the string {0}", charList.Count);
Console.WriteLine("We should have the last {0} characters removed", charList.Count - x);
Console.WriteLine(s.Substring(0, x + 1);
Console.ReadLine();
}
}
here we store the value the user entered into s, find the last index of a letter, and then Substring through that letter when writing out to the console.
string s = console.ReadLine();
s = s.Substring(0, s.ToList().FindLastIndex(char.IsLetter) + 1);
You also can use a function of string called SubString, to get everything from the first to the last letter index.
Here's a pretty inefficient way to do it (just for fun!)
var trimmedInput = string.Join("", input.Reverse().SkipWhile(x => !char.IsLetter(x)).Reverse());
You could use this extension:
public static string TrimLettersLeft(this string input)
{
int lastLetterIndex = -1;
for (int i = input.Length - 1; i >= 0; i--)
{
if (Char.IsLetter(input[i]))
{
lastLetterIndex = i;
break;
}
}
if( lastLetterIndex == -1)
return input;
else
return input.Substring(0, lastLetterIndex + 1);
}
Input: test...abc...
Output: test...abc
DEMO
Solution will be like this.
string charList = "string..."; //any string place here
int x = charList.LastIndexOf(charList.Last(char.IsLetter));
String str = charList.ToString().Substring(0, x + 1);
This will match every word character (A-Z, 0-9 and _):
string Input = Console.ReadLine();
string Userinput = String.Empty;
Regex TextSearch = new Regex(#"\w*");
if(TextSearch.IsMatch(Input))
Userinput = TextSearch.Match(Input).Groups[0].Value;
else
// No valid Input
What I believe would be the shortest, simplest option:
Edit: A comment pointed out an initial error here, so I added a little fix. Should work nicely now (might not be the optimal solution, but I thought it was a fun an simple solution anyway):
var userInput = Console.ReadLine();
Console.WriteLine(new string(userInput.Reverse()
.SkipWhile(c => !char.IsLetter(c))
.Reverse()
.ToArray()));
this code in Beginning C# 3.0: An Introduction to Object Oriented Programming
this is a program that has the user enter a couple of sentences in a multi - line textbox and then count how many times each letter occurs in that text
private const int MAXLETTERS = 26; // Symbolic constants
private const int MAXCHARS = MAXLETTERS - 1;
private const int LETTERA = 65;
.........
private void btnCalc_Click(object sender, EventArgs e)
{
char oneLetter;
int index;
int i;
int length;
int[] count = new int[MAXLETTERS];
string input;
string buff;
length = txtInput.Text.Length;
if (length == 0) // Anything to count??
{
MessageBox.Show("You need to enter some text.", "Missing Input");
txtInput.Focus();
return;
}
input = txtInput.Text;
input = input.ToUpper();
for (i = 0; i < input.Length; i++) // Examine all letters.
{
oneLetter = input[i]; // Get a character
index = oneLetter - LETTERA; // Make into an index
if (index < 0 || index > MAXCHARS) // A letter??
continue; // Nope.
count[index]++; // Yep.
}
for (i = 0; i < MAXLETTERS; i++)
{
buff = string.Format("{0, 4} {1,20}[{2}]", (char)(i + LETTERA)," ",count[i]);
lstOutput.Items.Add(buff);
}
}
I do not understand this line
count[index]++;
and this line of code
buff = string.Format("{0, 4} {1,20}[{2}]", (char)(i + LETTERA)," ",count[i]);
count[index]++; means "add 1 to the value in count at index index". The ++ is specifically known as incrementing. What the code is doing is tallying the number of occurrences of a letter.
buff = string.Format("{0, 4} {1,20}[{2}]", (char)(i + LETTERA)," ",count[i]); is formatting a line of output. With string.Format, you first pass in a format specifier that works like a template or form letter. The parts between { and } specify how the additional arguments passed into string.Format are used. Let me break down the format specification:
{0, 4} The first (index 0) argument (which is the letter, in this case).
The ,4 part means that when it is output, it should occupy 4 columns
of text.
{1,20} The second (index 1) argument (which is a space in this case).
The ,20 is used to force the output to be 20 spaces instead of 1.
{2} The third (index 2) argument (which is the count, in this case).
So when string.Format runs, (char)(i + LETTERA) is used as the first argument and is plugged into the {0} portion of the format. " " is plugged into {1}, and count[i] is plugged into {2}.
count[index]++;
That's a post-increment. If you were to save the return of that it would be count[index] prior to the increment, but all it basically does is increment the value and return the value prior to the increment. As for the reason why there is a variable inside square brackets, it is referencing a value in the index of an array. In other words, if you wanted to talk about the fifth car on the street, you may consider something like StreetCars(5). Well, in C# we use square brackets and zero-indexing, so we would have something like StreetCars[4]. If you had a Car array call StreetCars you could reference the 5th Car by using the indexed value.
As for the string.Format() method, check out this article.
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();