I'm making a program which reverses words to sdrow.
I understand that for it to work it needs to be written this way.
I'm more interested on WHY it has to be this way.
Here is my code:
Console.WriteLine("Enter a word : ");
string word = Console.ReadLine();
string rev = "";
int length;
for (length = word.Length - 1; length >= 0; length--)
{
rev = rev + word[length];
}
Console.WriteLine("The reversed word is : {0}", rev);
My questions are:
a) why you must use quotes to initialize your string
b) Why must you start your loop at one less than the total length of your string
c) How arrayname[int] works
I'm pretty new to C# and this site, as well. I hope my questions make sense and that I've asked them in the correct and proper way.
Thank you for your time!
This is how I've interpreted your question.
You want to know why you must use quotes to initialize your string
Why must you start your loop at one less than the total length of your string
How arrayname[int] works
I think that the best way to explain this to you is to go through your code, and explain what it does.
Console.WriteLine("Enter a word : ");
The first line of code prints Enter a word : into the console.
string word = Console.ReadLine();
This line "reads" the input from the console, and puts it into a string called word.
string rev = "";
This initiates a string called rev, setting it's value to "", or an empty string. The other way to initiate the string would be this:
string rev;
That would initiate a string called rev to the value of null. This does not work for your program because rev = rev + word[length]; sets rev to itself + word[length]. It throws an error if it is null.
The next line of your code is:
int length;
That sets an int (which in real life we call an integer, basically a number) to the value of null. That is okay, because it gets set later on without referencing itself.
The next line is a for loop:
for (length = word.Length - 1; length >= 0; length--)
This loop sets an internal variable called length to the current value of word.Length -1. The second item tells how long to run the loop. While the value of length is more than, or equal to 0, the loop will continue to run. The third item generally sets the rate of increase or decrease of your variable. In this case, it is length-- that decreases length by one each time the loop runs.
The next relevant line of code is his:
rev = rev + word[length];
This, as I said before sets rev as itself + the string word at the index of length, whatever number that is at the time.
At the first run through the for loop, rev is set to itself (an empty string), plus the word at the index of length - 1. If the word entered was come (for example), the index 0 would be c, the index 1 would be o, 2 would be m, and 3 = e.
The word length is 4, so that minus one is 3 (yay - back to Kindergarten), which is the last letter in the word.
The second time through the loop, length will be 2, so rev will be itself (e) plus index 2, which is m. This repeats until length hits -1, at which point the loop does not run, and you go on to the next line of code.
...Which is:
Console.WriteLine("The reversed word is : {0}", rev);
This prints a line to the console, saying The reversed word is : <insert value of rev here> The {0} is an internal var set by the stuff after the comma, which in this case would be rev.
The final output of the program, if you inserted come, would look something like this:
>Enter a word :
>come
>
>The reversed word is : emoc
a) you must to initialize or instantiate the variable in order to can work with it. In your case is better to use and StringBuilder, the string are inmutable objects, so each assignement means to recreate a new string.
b) The arrays in C# are zero index based so their indexes go from zero to length -1.
c) An string is an characters array.
Any case maybe you must to try the StringBuilder, it is pretty easy to use
I hope this helps
a) you need to initialize a variable if you want to use it in an assignment rev = rev + word[length];
b) you are using a for loop which means that you define a start number length = word.Length - 1, a stop criteria length >= 0 and a variable change length--
So lenght basically descends from 5 to 0 (makes 6 loops). The reason is that Arrays like 'string' a char[] are zerobased indexed.. means that first element is 0 last is array.Length - 1
c) So a string is basically a chain of char's.. with the []-Operator you can access a single index. The Return Type of words[index] is in this case a character.
I hope it helped
a) You need to first instantiate the string rev before you can assign it values in the loop. You could also say "string rev = String.Empty". You are trying to add word to rev and if you don't tell it first that rev is an empty string it doesn't know what it is adding word to.
b) The characters of the string have indexes to show which position they appear in the string. These indexes start at 0. So you're first character will have an index of 0. If the length of your string is 6 then the last character's index will be 5. So length - 1 will give you the value of the last character's index which is 5. A c# for loop uses the following parameters
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
where "int i = 0;" is the starting index; "i < 10" tells the loop when to stop looping; and "i++" tells it to increment i (the index) after each loop.
So in your code you are saying start at the last character of my string; perform this loop while there are still characters in the string; and decrease the index of the string after each loop so the next loop will look at the previous character in the string.
c) word[length] then in this scenario is saying add the character that has the position with index "length" to the rev string. This will basically reverse the word.
As usual you can do it in linq and avoid the (explicit) loops
using System;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a word : ");
string word = Console.ReadLine();
Console.WriteLine("The reversed word is : {0}", new string (word.Reverse().ToArray()));
Console.ReadLine();
}
}
}
var reversedWords = string.Join(" ",
str.Split(' ')
.Select(x => new String(x.Reverse().ToArray())));
Take a look here :
Easy way to reverse each word in a sentence
Related
I have code which checks if a word if a palindrome or not. Within the for loop there is a -1 value. Can someone explain to me why -1 is used after the name.Length in c#
public static void Main()
{
string name = "Apple";
string reverse = string.Empty;
for (int i = name.Length - 1; i >= 0; i--)
{
reverse +=name[i];
}
if (name == reverse)
{
Console.WriteLine($"{name} is palindrome");
}else
{
Console.WriteLine($"{name} is not palindrome");
}
That's because whoever wrote the code, wanted to write:
reverse += name[i];
String operator [] takes values from 0 upto (string's length-1). If you pass length or more, you will get an exception. So, code's author had to ensure that i==Length won't be ever passed there. So it starts from Length-1 and counts downwards.
Also, note that the other bound of i is 0 (>=, not >, so 0 is included), so the loop visits all values from 0 to length-1, so it visits all characters from the string. Job done.
However, it doesn't have to be written in that way. The only thing is to ensure that the string operator [] wont see values of of its range. Compare this loop, it's identical in its results:
for (int i = name.Length; i >= 1; i--)
{
reverse += name[i-1];
}
Note that I also changed 0 to 1.
Of course, it's also possible to write a loop with the same effects in a lot of other ways.
The first element in an array is at the index 0 (array[0]). Because the indexing starts at 0 instead of 1 it means that the final element in the array will be at index array.Length-1.
If you had the word and then your array would look like:
name[0] = 'a'
name[1] = 'n'
name[2] = 'd'
the name.Length would equal 3. As you can see, there isn't an element at index 3 in the array so you need to subtract 1 from the length of the array to access the last element.
The for loop in your example starts with the last element in the array (using i as the index). If you tried to set i to i = name.Length then you would get an index out of bounds error because there isn't an element at the position name.Length.
String operator [] takes values from 0. The first element in an string is at the index 0, so we need to adjust by subtracting one.
For Example:
string str = "test";
int length = str.length; //Length of the str is 4. (0 to 3)
I have a string which contains a lot of useless information after the first char: space. So I built a StringBuilder to remove unnecesary characters after the first space.
public static string Remove(string text)
{
int index1 = text.IndexOf(' ');
int index2 = text.Lenght;
StringBuilder sv = new StringBuilder(text.Lenght);
sv.Append(text);
sv.Remove(index1, index2);
string text2 = sv.ToString();
return text2;
}
Can somebody explain why this throws me an error? Thank you!
The reason for this exception is that you misunderstood the purpose of the second parameter: rather than specifying the ending index, it specifies the length of the segment to be removed.
Since your code is passing the length of the entire text string, the only valid input for the first parameter would be zero. To pass a proper value, subtract the first index from the second index, and add 1 to the result.
Note: It looks like you are removing everything from the string starting at the first space ' '. A simpler way of doing it would be with substring:
int index = text.IndexOf(' ');
return index >= 0 ? text.Substring(0, index) : text;
The documentation for Remove says it all - only one exception is raised for that method
ArgumentOutOfRangeException: If startIndex or length is less than zero, or startIndex + length is greater than the length of this instance.
So one of two things is going on
Your string does not contain a space (startIndex will be less than zero)
The startIndex+length is greater than the total length of the string.
Crucially, with the code you've posted 1. above could sometimes be true, and 2. will always be true! You should have done index2-index1 for the second parameter.
Console.WriteLine("Enter the plain text: ");
string ptxt=Console.ReadLine();
ptxt= ptxt.ToUpper();
char[] ptxtarr = ptxt.ToCharArray();
for(i=0; i<=ptxt.Length;i++)
{
if(char.IsLetter(ptxtarr[i]))
{
nptxtarr.Add(ptxtarr[j]);
j++;
}
}
getting error at ptxtarr[i] for the last value of the array for string "hello world"
also char.Isletter() should select only alphabets but it also selects space, why so?
screenshot
Why do you use j in the if clause?
it should be like this
Console.WriteLine("Enter the plain text: ");
string ptxt=Console.ReadLine();
ptxt= ptxt.ToUpper();
char[] ptxtarr = ptxt.ToCharArray();
for(i=0; i<=ptxt.Length;i++)
{
if(char.IsLetter(ptxtarr[i]))
{
nptxtarr.Add(ptxtarr[i]);
}
}
it is troublesome using that j variable as it will add those space and you get string with less character as the space count
for example you have string 'hello world' using your code it will return 'hello worl' The reason is when your code encountered space, it will not increment the j and therefore the added char is the space which is next char after your last added char
Few points.
Arrays in C# follows zero based index.
j<=ptxt.Lengthcauses your inner statement to look for n+1 element in n length array.
Multiple ways we can fix this problem.
for(i=0; i<ptxt.Length;i++)
{
if(char.IsLetter(ptxtarr[i]))
{
// logic here
}
}
or
foreach (char c in ptxtarr)
{
if(char.IsLetter(c))
{
// logic here
}
}
Alternateively, we can also use Linq.
if(ptxtarr.All(char.IsLetter)) // Verifies every character is a letter.
{
// logic here.
nptxtarr = ptxtarr
}
The char[] Follows Zero based indexing. that means if the array having three elements the indices will be 0,1,2. and the length of the array will be 3 which denotes the number of elements in the array.
What you have to do to solve your problem is :
Change your Looping condition as like this:
for(i=0; i<ptxt.Length;i++)
{
//Do your stuff here
}
Use foreach instead for this:
foreach (char c in ptxtarr)
{
if(char.IsLetter(c))
{
nptxtarr.Add(c);
}
}
Oh please stop this nonsense.
The reason it appears that Char.IsLetter() thinks that spaces are characters is that you're index is not your incrementor. You increment i in your for loop declaration, but you're using a separate letter, j, when you select from your character array. Since you only increment j when you hit a letter, but i increments on its own, your loop will correctly skip the space, but then still include it in your result array since j has not been incremented.
For future reference, include all relevant code. We're clearly missing the declarations for j and nptxtarr.
This will accomplish what you're looking to do without the unsightly loops or bugs:
Console.WriteLine("Enter the plain text: ");
char[] letters = Console.ReadLine()
.ToUpper()
.Where(c => Char.IsLetter(c))
.ToArray();
That will produce an array of upper case letters from one line of user input. What you do with it is up to you.
Why this works:
string is a series of unicode characters (look at the tooltip). It's enumerable and supports the IEnumerable interface. This takes the input from the console, converts it to upper case, enumerates through the characters that make up the string which qualify as Char.IsLetter and spits out an array of those characters.
I am trying to split the data in this array, but it keeps giving me this error:
index out of bounds.
The size of the array is 10. The line of code that is creating the error is
int score = int.Parse(scoreInfo[1]);
This is the code that I have:
static void Main(string[] args)
{
const int SIZE = 10;
for (int j = 0; j < SIZE; j++)
{
// prompt the user
Console.WriteLine("Enter player name and score on one line");
Console.WriteLine("seperated by a space.");
// Read one line of data from the file and save it in inputStr
string inputStr = Console.ReadLine();
// The split method creates an array of two strings
string[] scoreInfo = inputStr.Split();
// Parse each element of the array into the correct data type.
string name = (scoreInfo[0]);
int score = int.Parse(scoreInfo[1]);
if (inputStr == "")
{
Console.WriteLine(scoreInfo[j]);
}
}
Console.ReadLine();
}
A few things of note. You are using SIZE to denote how many iterations your loop should make. It is not the size of your array. Your array is only going to be large as the split makes it. If you split with a space as the delimiter, you're going to have 2 objects in the array at indices 0 and 1.
That last section where you're saying to write scoreInfo[j] will fail as soon as j is larger than 1.
I tried your code using a constant, something like "Guy 19". The .Split() method will break up your input string based on spaces. If you're not entering a space followed by a number, then your scoreInfo[1] will be empty and parsing will fail.
Try adding a break point after your .Split() to determine if scoreInfo is correctly split into a size 2 array, with [0] being the name of the player and [1] being an integer score. If you're entering a name like "FirstName LastName 20" then the information at position [1] is not going to be an integer and the parsing will also fail.
Your for-loop is sort of puzzling, are you looping through 10 times for a team of 10 players? You could put your dialog in a while loop and break out when parsing fails or the user types something like "exit".
So, what I'm trying to do this something like this: (example)
a,b,c,d.. etc. aa,ab,ac.. etc. ba,bb,bc, etc.
So, this can essentially be explained as generally increasing and just printing all possible variations, starting at a. So far, I've been able to do it with one letter, starting out like this:
for (int i = 97; i <= 122; i++)
{
item = (char)i
}
But, I'm unable to eventually add the second letter, third letter, and so forth. Is anyone able to provide input? Thanks.
Since there hasn't been a solution so far that would literally "increment a string", here is one that does:
static string Increment(string s) {
if (s.All(c => c == 'z')) {
return new string('a', s.Length + 1);
}
var res = s.ToCharArray();
var pos = res.Length - 1;
do {
if (res[pos] != 'z') {
res[pos]++;
break;
}
res[pos--] = 'a';
} while (true);
return new string(res);
}
The idea is simple: pretend that letters are your digits, and do an increment the way they teach in an elementary school. Start from the rightmost "digit", and increment it. If you hit a nine (which is 'z' in our system), move on to the prior digit; otherwise, you are done incrementing.
The obvious special case is when the "number" is composed entirely of nines. This is when your "counter" needs to roll to the next size up, and add a "digit". This special condition is checked at the beginning of the method: if the string is composed of N letters 'z', a string of N+1 letter 'a's is returned.
Here is a link to a quick demonstration of this code on ideone.
Each iteration of Your for loop is completely
overwriting what is in "item" - the for loop is just assigning one character "i" at a time
If item is a String, Use something like this:
item = "";
for (int i = 97; i <= 122; i++)
{
item += (char)i;
}
something to the affect of
public string IncrementString(string value)
{
if (string.IsNullOrEmpty(value)) return "a";
var chars = value.ToArray();
var last = chars.Last();
if(char.ToByte() == 122)
return value + "a";
return value.SubString(0, value.Length) + (char)(char.ToByte()+1);
}
you'll probably need to convert the char to a byte. That can be encapsulated in an extension method like static int ToByte(this char);
StringBuilder is a better choice when building large amounts of strings. so you may want to consider using that instead of string concatenation.
Another way to look at this is that you want to count in base 26. The computer is very good at counting and since it always has to convert from base 2 (binary), which is the way it stores values, to base 10 (decimal--the number system you and I generally think in), converting to different number bases is also very easy.
There's a general base converter here https://stackoverflow.com/a/3265796/351385 which converts an array of bytes to an arbitrary base. Once you have a good understanding of number bases and can understand that code, it's a simple matter to create a base 26 counter that counts in binary, but converts to base 26 for display.