Difference between revisions of "Accessing each character of a string"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
 
(2 intermediate revisions by the same user not shown)
Line 14: Line 14:
 
Console.ReadLine();
 
Console.ReadLine();
 
</syntaxhighlight>
 
</syntaxhighlight>
 +
 +
Line 1 & 2 will prompt for the word and store it in a variable called word.
 +
 +
Line 4 is a for loop which will start at zero and continue while `i` is less than the length of the word.
 +
 +
Line 6 uses `i` to access that specific character of `word`. the square brackets `[]` is always about accessing a specific element.
 +
 +
The benefit of using this method is that changes can be made to `word` within this loop.
 +
 +
==Method 2==
 +
<syntaxhighlight lang=csharp line>
 +
Console.WriteLine("please enter a word:");
 +
string word = Console.ReadLine();
 +
 +
foreach(char c in word)
 +
{
 +
Console.WriteLine(c);
 +
}
 +
 +
Console.ReadLine();
 +
</syntaxhighlight>
 +
 +
Line 1 & 2 will prompt for the word and store it in a variable called word.
 +
 +
Line 4 is a for loop which will cycle through each character in the word in turn. The current character will be called `c`.
 +
 +
Line 6 simply outputs the value of `c`.
 +
 +
The benefit of using this method is that it requires less knowledge to create. However this doesn't allow the value of `c` to be changed.

Latest revision as of 07:44, 15 June 2023

Accessing the individual characters of a string is a common part of any Section B question. This page looks at the different methods you can use to achieve this.

Method 1

1 Console.WriteLine("please enter a word:");
2 string word = Console.ReadLine();
3 		
4 for(int i=0; i < word.Length;i++)
5 {
6 	Console.WriteLine(word[i]);
7 }
8 	
9 Console.ReadLine();

Line 1 & 2 will prompt for the word and store it in a variable called word.

Line 4 is a for loop which will start at zero and continue while `i` is less than the length of the word.

Line 6 uses `i` to access that specific character of `word`. the square brackets `[]` is always about accessing a specific element.

The benefit of using this method is that changes can be made to `word` within this loop.

Method 2

1 Console.WriteLine("please enter a word:");
2 string word = Console.ReadLine();
3 		
4 foreach(char c in word)
5 {
6 	Console.WriteLine(c);
7 }
8 
9 Console.ReadLine();

Line 1 & 2 will prompt for the word and store it in a variable called word.

Line 4 is a for loop which will cycle through each character in the word in turn. The current character will be called `c`.

Line 6 simply outputs the value of `c`.

The benefit of using this method is that it requires less knowledge to create. However this doesn't allow the value of `c` to be changed.