The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.
You can search for a particular letter in a string using the indexOf() method of the String class. This method which returns a position index of a word within the string if found. Otherwise it returns -1.
The Java String charAt(int index) method returns the character at the specified index in a string. The index value that we pass in this method should be between 0 and (length of string-1). For example: s. charAt(0) would return the first character of the string represented by instance s.
The charAt() method returns the character at a specified index (position) in a string. The index of the first character is 0, the second 1, ...
The method you're looking for is charAt
. Here's an example:
String text = "foo";
char charAtZero = text.charAt(0);
System.out.println(charAtZero); // Prints f
For more information, see the Java documentation on String.charAt
. If you want another simple tutorial, this one or this one.
If you don't want the result as a char
data type, but rather as a string, you would use the Character.toString
method:
String text = "foo";
String letter = Character.toString(text.charAt(0));
System.out.println(letter); // Prints f
If you want more information on the Character
class and the toString
method, I pulled my info from the documentation on Character.toString.
You want .charAt()
Here's a tutorial
"mystring".charAt(2)
returns s
If you're hellbent on having a string there are a couple of ways to convert a char to a string:
String mychar = Character.toString("mystring".charAt(2));
Or
String mychar = ""+"mystring".charAt(2);
Or even
String mychar = String.valueOf("mystring".charAt(2));
For example.
None of the proposed answers works for surrogate pairs used to encode characters outside of the Unicode Basic Multiligual Plane.
Here is an example using three different techniques to iterate over the "characters" of a string (incl. using Java 8 stream API). Please notice this example includes characters of the Unicode Supplementary Multilingual Plane (SMP). You need a proper font to display this example and the result correctly.
// String containing characters of the Unicode
// Supplementary Multilingual Plane (SMP)
// In that particular case, hieroglyphs.
String str = "The quick brown π₯ jumps over the lazy ππΏπ
π‘";
The first solution is a simple loop over all char
of the string:
/* 1 */
System.out.println(
"\n\nUsing char iterator (do not work for surrogate pairs !)");
for (int pos = 0; pos < str.length(); ++pos) {
char c = str.charAt(pos);
System.out.printf("%s ", Character.toString(c));
// ^^^^^^^^^^^^^^^^^^^^^
// Convert to String as per OP request
}
The second solution uses an explicit loop too, but accessing individual code points with codePointAt and incrementing the loop index accordingly to charCount:
/* 2 */
System.out.println(
"\n\nUsing Java 1.5 codePointAt(works as expected)");
for (int pos = 0; pos < str.length();) {
int cp = str.codePointAt(pos);
char chars[] = Character.toChars(cp);
// ^^^^^^^^^^^^^^^^^^^^^
// Convert to a `char[]`
// as code points outside the Unicode BMP
// will map to more than one Java `char`
System.out.printf("%s ", new String(chars));
// ^^^^^^^^^^^^^^^^^
// Convert to String as per OP request
pos += Character.charCount(cp);
// ^^^^^^^^^^^^^^^^^^^^^^^
// Increment pos by 1 of more depending
// the number of Java `char` required to
// encode that particular codepoint.
}
The third solution is basically the same as the second, but using the Java 8 Stream API:
/* 3 */
System.out.println(
"\n\nUsing Java 8 stream (works as expected)");
str.codePoints().forEach(
cp -> {
char chars[] = Character.toChars(cp);
// ^^^^^^^^^^^^^^^^^^^^^
// Convert to a `char[]`
// as code points outside the Unicode BMP
// will map to more than one Java `char`
System.out.printf("%s ", new String(chars));
// ^^^^^^^^^^^^^^^^^
// Convert to String as per OP request
});
When you run that test program, you obtain:
Using char iterator (do not work for surrogate pairs !)
T h e q u i c k b r o w n ? ? j u m p s o v e r t h e l a z y ? ? ? ? ? ? ? ?
Using Java 1.5 codePointAt(works as expected)
T h e q u i c k b r o w n π₯ j u m p s o v e r t h e l a z y π πΏ π
π‘
Using Java 8 stream (works as expected)
T h e q u i c k b r o w n π₯ j u m p s o v e r t h e l a z y π πΏ π
π‘
As you can see (if you're able to display hieroglyphs properly), the first solution does not handle properly characters outside of the Unicode BMP. On the other hand, the other two solutions deal well with surrogate pairs.
You're pretty stuck with substring()
, given your requirements. The standard way would be charAt()
, but you said you won't accept a char data type.
You could use the String.charAt(int index)
method result as the parameter for String.valueOf(char c).
String.valueOf(myString.charAt(3)) // This will return a string of the character on the 3rd position.
A hybrid approach combining charAt
with your requirement of not getting char could be
newstring = String.valueOf("foo".charAt(0));
But that's not really "neater" than substring()
to be honest.
It is as simple as:
String charIs = string.charAt(index) + "";
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