Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Loops are also a great way to work with String values.
Let's say we wanted to count the number of times the letter "a" appears in a string. We need to look at each character in the string and check if it is an "a".
We can do this using the code below:
Let's say we wanted to modify the string and replace all the a's with *'s. How we can do this?
We'll first need to declare a new empty string to hold the new string.
newString = "".
We can then iterate over each character in our string and:
- If the character is an a, then we add * to our new string
- else we add the current character to our new String.
Now it's your turn. In the program below, replace all the "a"s with the letter "z", and create a variable named numberOfZs and set that equal to the number of "z"s that apprear in the new String.