To access character of a string in Java, use the charAt() method. The position is to be added as the parameter. String str = "laptop"; Let's find the character at the 4th position using charAt() method.
The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.
A String containing a single character is not the same as a char. They both can be declared using quotes (single quotes for chars and double quotes for Strings), but they are very different. At a high level, a way to think about it is that a String is an Object that allows you to operate on a sequence of chars.
Because strings, like lists and tuples, are a sequence-based data type, it can be accessed through indexing and slicing.
For statements
For a string value, the "range" clause iterates over the Unicode code points in the string starting at byte index 0. On successive iterations, the index value will be the index of the first byte of successive UTF-8-encoded code points in the string, and the second value, of type rune, will be the value of the corresponding code point. If the iteration encounters an invalid UTF-8 sequence, the second value will be 0xFFFD, the Unicode replacement character, and the next iteration will advance a single byte in the string.
For example,
package main
import "fmt"
func main() {
str := "Hello"
for _, r := range str {
c := string(r)
fmt.Println(c)
}
fmt.Println()
for i, r := range str {
fmt.Println(i, r, string(r))
}
}
Output:
H
e
l
l
o
0 72 H
1 101 e
2 108 l
3 108 l
4 111 o
package main Use Printf to indicate you want to print characters.
import "fmt"
func main() {
str := "Hello"
for i, elem := range str {
fmt.Printf("%d %c %c\n", i, str[i], elem)
}
}
The way you are iterating over the characters in the string is workable (although str[i] and elem are the duplicative of each other). You have the right data.
In order to get it to display correctly, you just need to output with the right formatting (i.e. interpreted as a unicode character rather than an int).
Change:
fmt.Println(i, str[i], elem)
to:
fmt.Printf("%d %c %c\n", i, str[i], elem)
%c
is the character represented by the corresponding Unicode code point per the Printf doc: http://golang.org/pkg/fmt/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With