String Manipulation: When you need to make changes to text inside your code… like removing certain letter combinations or adding punctuation marks omitted by accident, CharAt will come in handy when looking up where those specific letters would fall. For example, if I want to remove all occurrences of “the”, I could use this expression below:
“the”.length == 0 ~~~=> will be true if CharAt(‘e’) is not ‘t’ OR CharAt(‘h’) is not ‘d’. So all I have to do is use that expression and then replace the character with whatever I want.
A character at the specified index. If you specify an out-of-range number, it will return us nothing but one UTF-16 code unit (exactly). If we want to know a specific character and its corresponding value in Unicode encoding, then this is where charAt() comes into play!
– First, we need to create a string with a length of the number of characters in our sentence so that it can store each one.
– Then, we can iterate through the string, asking for each character. CharAt() will return a number (from 0 to length – one) that corresponds with an index in our string. So when it returns zero, that means “the” is at position 0 and so on…
When the string index is specified, extracting one character from that position creates an instance of the String type. The range for this argument starts at 0 and goes to length minus one, so if no specific index number is given, it will start with zero, which can be used as the default value.
– CharAt(0) will return the character at position 0
– CharAt(-11) would create an instance of String type with length – 11. The first letter in that string is going to be a “P”.
– CharAt(‘foo’) returns “f” because it has not reached the end yet, and there are more characters after ‘o’. It does not stop until it reaches a blank space or another non-‘a’ character, so even if you use CharAt(“foobar”), then it’ll still keep counting past z for as long as letters exist within that word.
The range starts at zero, which means that this function assumes its default starting point of zero when no value is given.
This blog post will cover the function of CharAt and how it can be used to get a character from an input string. A second section will provide examples of how this is useful for developers and some code samples so that you can see what I’m talking about in action.
If you have not found what you are looking for, please feel free to contact us using our live chat on this page or send us your question through email. Just click one of those two buttons below, and we’ll be happy to help! 🙂