- Methods
- Generating a random string
- String comparison:
equals()
or ==
?
The class is
String
very often used by programmers, so it should be learned very well.
Remember that class objects
String
are immutable. So when you think you are changing a string, you are actually creating a new string. Java has special classes
StringBuffer
and
StringBuilder
that allow changes to a string. The classes
String
,
StringBuffer
,
StringBuilder
are defined in the
java.lang package and are available automatically without an import declaration. All three classes implement the interface
CharSequence
. Creating a string is very simple. For example, you can do this:
String aboutCat = "Кот - это звучит гордо, а если наступить на хвост, то громко";
You can create an array of strings:
String[] cats = {"Васька", "Barsik", "Murzik"};
You can create an empty class object
String
:
String str = new String();
You can create a string via a character array:
char[] chars = { 'c', 'a', 't' };
String str = new String(chars);
There is also a constructor that allows you to set the range of a character array. You need to specify the start of the range and the number of characters to use:
char[] chars = {'c', 'a', 't', 'a', 'm', 'a', 'r', 'a', 'n' };
String str = new String(chars, 0, 3);
You can create a class object
String
from a classes object
StringBuffer
using
StringBuilder
the following constructors:
String(StringBuffer an object_StrBuf)
String(StringBuilder an object_StrBuild)
Operators +
and += forString
In Java, the plus sign (
+
) means string concatenation, in other words, combining strings.
String cat = "Кот";
String name = "Васька";
String fullname = cat + " " + name;
If one of the operands in an expression contains a string, then the other operands must also be strings. Therefore, Java itself can cast variables to a string representation, even if they are not strings.
int digit = 4;
String paws = " лапы";
String aboutcat = digit + paws;
За кулисами Java за нас преобразовало число 4 в строку "4"
Formatting strings
Let's assume we have a string resource:
<string name="aboutcat">У кота по имени Барсик четыре лапы, один хвост. Ему 5 лет</string>
To display this string programmatically in the element
TextView
, you can use the code:
TextView tvCatsInfo = (TextView)findViewById(R.id.textView1);
tvCatsInfo.setText(R.string.aboutcat);
Imagine that you have several cats. You can, of course, have your own line for each cat. But the lines are very similar, only the names and ages change. You can also change the number of paws and tails (what are you smoking?). In such cases, you can apply string formatting. We need to determine the words that we will change and replace them with a special set of characters that begin with a percent symbol, then a number incrementing by one, then
$s
for strings or
$d
for numbers. So let's change our string resource like this:
<string name="aboutcat">У кота по имени %1$s %2$s лапы, %3$s хвост. Ему %4$d лет</string>
Let's make changes to the code:
String strBarsik = "Barsik";
String strPaws = "четыре";
String strTail = "one";
int year = 5;
String strCats = getResources().getString(R.string.aboutcat);
String strFinal = String.format(strCats, strBarsik, strPaws, strTail, year);
tvCatsInfo.setText(strFinal);
If you have a cat Vaska and he is six years old, then add two variables and format the line
String strVaska = "Васька";
year = 6;
String strFinal = String.format(strCats, strVaska, strPaws, strTail, year);
tvCatsInfo.setText(strFinal);
Here's a simple formatting example. Remember it and use it in the right places.
String resource
It is advisable to store strings in resources. Programmatically accessing a string resource is done like this:
String catName = getResources().getString(R.string.barsik);
Extract strings from string arrays in resources
Let's say you have a string array defined in the
strings.xml file called
cats_array
. Then you can access rows from resources like this:
Resources res = getResources();
String[] cats = res.getStringArray(R.array.cats_array);
Methods
public char charAt (int index)
Returns the character at the specified offset in this string. The countdown starts from 0. There is no need to use negative and non-existent values, be more serious. To extract multiple characters use
getChars()
.
String testString = "Котёнок";
char myChar = testString.charAt(2);
tv.setText(Character.toString(myChar));
public int codePointAt(int index)
Returns the Unicode character at the given index
String testString = "Котёнок";
int myChar = testString.codePointAt(3);
tv.setText(String.valueOf(myChar));
public int codePointBefore(int index)
Returns the Unicode character that precedes the given index
String testString = "Котёнок";
int myChar = testString.codePointBefore(4);
tv.setText(String.valueOf(myChar));
public int codePointCount(int start, int end)
Calculates the number of Unicode characters between positions
start
and
end
String testString = "Котёнок";
int myChar = testString.codePointCount(0, 3);
tv.setText(String.valueOf(myChar));
public int compareTo(String string)
Compares the specified string using Unicode character values and calculates which string is less than, equal to, or greater than the next. Can be used for sorting. Case is taken into account. If the strings match, then 0 is returned, if less than zero, then the calling string is less than string
string
, if greater than zero, then the calling string is greater than string
string
. Upper case words are placed above lower case words.
String testString = "Котёнок";
if (testString.compareTo("котёнок") == 0) {
tvInfo.setText("Строки равны");
} else {
tvInfo.setText("Строки не равны. Возвращено"
+ testString.compareTo("котёнок"));
}
Let's sort the array of strings using bubble sort.
String[] poem = { "Мы", "везём", "с", "собой", "кота" };
for (int j = 0; j < poem.length; j++) {
for (int i = j + 1; i < poem.length; i++) {
if (poem[i].compareTo(poem[j]) < 0) {
String temp = poem[j];
poem[j] = poem[i];
poem[i] = temp;
}
}
System.out.println(poem[j]);
}
As a result we get:
Мы
везём
кота
с
собой
As you can see,
changing the places of the terms does not change the sorting sum of the cats.
public int compareToIgnoreCase (String string)
Compares the specified string using Unicode character values, insensitive to case.
String testString = "Котёнок";
if (testString.compareToIgnoreCase("котёнок") == 0) {
tv.setText("Строки равны");
} else {
tv.setText("Строки не равны. Возвращено"
+ testString.compareTo("котёнок"));
}
public String concat (String string)
Concatenates a string with the specified string. A new string is returned that contains the concatenation of the two strings. Note that the method name itself contains a cat!
String testString = "Сук";
String newString = testString.concat("кот");
tv.setText(newString);
The method performs the same function as the operator
+
and could be written
Сук + кот
. But a real cat person will use the "cat" method.
public boolean contains (CharSequence cs)
Determines whether a string contains a sequence of characters in
CharSequence
String testString = "котёнок";
if(testString.contains("кот")){
infoTextView.setText("В слове котёнок содержится слово кот!");
}
public static String copyValueOf (char[] data, int start, int length)
Creates a new string containing the specified characters from the array
Data
starting at position
start
(zero-based numbering) of length
length .
public static String copyValueOf(char[] data)
Creates a new string containing characters from the specified array. Changing the array after the row has been created does not change the created row.
public boolean endsWith(String suffix)
Checks whether a string ends with
suffix
.
String str1 = "Суккот";
if(str1.endsWith("кот"))
infoTextView.setText("Слово заканчивается на котике");
else
infoTextView.setText("Плохое слово. Нет смысла его использовать");
public boolean equals (Object string)
Compares the specified object and a string and returns
true if the compared strings are equal, i.e. contains the same characters and in the same case-sensitive order.
String str1 = "Кот";
String str2 = "Кошка";
if(str1.equals(str2))
infoTextView.setText("Строки совпадают");
else
infoTextView.setText("Строки не совпадают");
The method is not to be confused with the operator
==
, which compares two object references and determines whether they refer to the same instance. See String Comparison:
equals()
or
==
?
public boolean equalsIgnoreCase(String string)
Compares the specified string with the source string in a case-insensitive manner and returns
true if they are equal. The AZ range is considered equal to the az range.
String str1 = "Кот";
String str2 = "кот";
if(str1.equalsIgnoreCase(str2))
infoTextView.setText("Строки совпадают");
else
infoTextView.setText("Строки не совпадают");
public static String format(Locale locale, String format, Object... args)
Returns a formatted string using the supplied format and arguments localized to the given scope. For example date or time
String.format("%.2f", floatValue);
We glue two words that appear on a new line. In this case, the second word is displayed in upper case.
String str1 = "Кот";
String str2 = "васька";
String strResult = String.format("%s\n%S", str1, str2);
infoTextView.setText(strResult);
Convert the number to octal system.
String str1 = "8";
int inInt = Integer.parseInt(str1);
String strResult = String.format("(Восьмеричное meaning): %o\n", inInt);
infoTextView.setText(strResult);
By analogy, we display in hexadecimal system
String str1 = "255";
int inInt = Integer.parseInt(str1);
String strResult = String.format("(Шестнадцатеричное meaning): %x\n", inInt);
infoTextView.setText(strResult);
For uppercase use
%X
, then
ff
it will be
FF
. For decimal system use
%d
. The date can also be displayed in different ways.
Date now = new Date();
Locale locale = Locale.getDefault();
infoTextView.setText(
String.format(locale, "%tD\n", now) +
String.format(locale, "%tF\n", now) +
String.format(locale, "%tr\n", now) +
String.format(locale, "%tz\n", now) +
String.format(locale, "%tZ\n", now));
public byte[] getBytes(String charsetName)
Returns a formatted string using the supplied format.
public void getBytes(int start, int end, byte[] data, int index)
and other overloads The method stores characters into a byte array, an alternative to the
getChars()
. Often used when exporting strings from various sources that use other Unicode characters. For example, Java by default works with 16-bit Unicode characters, and on the Internet, strings often use 8-bit Unicode, ASCII, etc.
public void getChars(int start, int end, char[] buffer, int index)
Method for extracting multiple characters from a string. You need to specify the index of the beginning of the substring (
start
), the index of the character following the end of the substring to be extracted ( end ). The array that receives the selected characters is in the
buffer parameter . The index in the array, starting from which the substring will be written, is passed in the
index parameter . Make sure that the array is large enough to contain all the characters in the specified substring.
String unusualCat = "Котёнок по имени Гав";
int start = 5;
int end = 12;
char[] buf = new char[end - start];
unusualCat.getChars(start, end, buf, 0);
infoTextView.setText(new String(buf));
public int hashCode()
Returns an integer that is the hash code for this object.
public int indexOf(int c)
Returns the number of the first encountered position with the specified index c.
String testString = "котёнок";
infoTextView.setText(String.valueOf(testString.indexOf("ё")));
public int indexOf (int c, int start)
Looks up the index from, starting at position
start
String testString = "котёнок";
infoTextView.setText(String.valueOf(testString.indexOf("ё", 4)));
public int indexOf (String string)
Searches for a string of characters
subString
String testString = "У окошка";
infoTextView.setText(String.valueOf(testString.indexOf("кошка")));
public int indexOf (String subString, int start)
Searches for a string of characters
subString
starting at position
start
String testString = "У окошка";
infoTextView.setText(String.valueOf(testString.indexOf("кошка", 2)));
public String intern ()
"Hashes" a string
public boolean isEmpty ()
Checks if the string is empty
if(catname.isEmpty()) {
}
This method appeared in API 9 (Android 2.1). For older devices, use
String.length() == 0
public int lastIndexOf (String string) и другие перегруженные версии
Returns the number of the last encountered position at the specified index. For example, you can get the file name without extension like this:
filename.toString().substring(0, filename.getString().lastIndexOf("."));
In this example, we get the position of the last point and get the substring before it.
public int length()
Returns the length of a string
String testString = "котёнок";
infoTextView.setText(String.valueOf(testString.length()));
public boolean matches(String regularExpression)
Checks if a string matches regular expressions.
public int offsetByCodePoints (int index, int codePointOffset)
Returns a position located at a distance
codePointOffset
after the starting position specified by the parameter.
index
public boolean regionMatches (int thisStart, String string, int start, int length)
The method compares the specified part of the string with another part of the string. You must specify the index of the beginning of the row range of the calling object of the class
String
. The string to be compared is passed in the parameter
string
. The index of the character starting from which the comparison needs to be performed is passed in the parameter
start
, and the length of the substring to be compared is passed in the parameter
length
.
public boolean regionMatches (boolean ignoreCase, int thisStart, String string, int start, int length)
Overloaded version. The method compares the specified part of a string with another part of the string, ignoring case.
public String replace(CharSequence target, CharSequence replacement) и другие перегруженные версии
Changes a character or sequence of characters
target
to
replacement
String testString = "whale";
infoTextView.setText(testString.replace("And", "о"));
public String replaceAll (String regularExpression, String replacement)
public String replaceFirst (String regularExpression, String replacement)
Removes the first characters using a regular expression. For example, if you need to remove zeros at the beginning of the numbers 001, 007, 000024, then you can use this call.
String s = "001234-cat";
String s = s.replaceFirst ("^0*", "");
public String[] split (String regularExpression) и другие перегруженные версии
Splits a string into an array of words. For example, there is a string Vaska Ryzhik Murzik Barsik and we want to get an array of cat names:
String catnames = "Васька Рыжик Мурзик Барсик";
String aCats[] = catnames.split(" ");
We get:
aCats[0] = Васька
aCats[1] = Рыжик
aCats[2] = Мурзик
aCats[3] = Барсик
public boolean startsWith(String prefix)
Checks if a string begins with characters
prefix
from the beginning of the string
String str1 = "котлета";
if(str1.startsWith("кот"))
infoTextView.setText("Слово содержит кота");
else
infoTextView.setText("Плохое слово. Нет смысла его использовать");
public boolean startsWith(String prefix, int start)
Checks whether the given string begins with characters
prefix
at the specified position.
String str1 = "Суккот";
if(str1.startsWith("кот", 3))
infoTextView.setText("Слово содержит кота");
else
infoTextView.setText("Плохое слово. Нет смысла его использовать");
public CharSequence subSequence (int start, int end)
Similar to the method
substring()
, but can be used for
CharSequence
.
public String substring(int start)
and other overloads Creates a new sequence/string with characters from the given string starting at position
start
to the end of the line/ending with the character at position
end
. The new line contains characters from
start
to end - 1, so we take one more character.
String testString = "скотина";
infoTextView.setText(testString.substring(1, 4));
public char[] toCharArray()
Copies the characters in this string to a character array. The same result can be obtained through the
getChars()
. The documentation does not recommend using this method, suggesting the
charAt()
.
String unusualCat = "Котёнок по имени Гав";
char[] yomoe = unusualCat.toCharArray();
infoTextView.setText(String.valueOf(yomoe[3]));
public String toLowerCase() и другие перегруженные версии
Converts a string to lower case. The default locale controls the conversion. String cat = "Cat"; String lower = cat.toLowerCase(); infoTextView.setText(lower);
public String toString ()
Returns a string. For the string itself, which itself is already a string, returning the string is pointless (oh, how I bent it). But this method is actually very useful for other classes.
public String toUpperCase()
Converts a string to upper case. The default locale controls the conversion.
String cat = "Кот";
String upper = cat.toUpperCase();
infoTextView.setText(upper);
public String trim()
Removes spaces at the beginning and end of a string.
String str = " Hello Kitty ".trim();
infoTextView.setText(str);
public static String valueOf(long value)
and other overloads Converts contents (numbers, objects, characters, character arrays) to a string.
int catAge = 7;
infoTextView.setText(String.valueOf(catAge));
Generating a random string
Let's say we need a random string of given characters.
private static final String mCHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
private static final int STR_LENGTH = 9;
Random random = new Random();
public void onClick(View view) {
TextView infoTextView = (TextView) findViewById(R.id.textViewInfo);
infoTextView.setText(createRandomString());
}
public String createRandomString() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < STR_LENGTH; i++) {
int number = random.nextInt(mCHAR.length());
char ch = mCHAR.charAt(number);
builder.append(ch);
}
return builder.toString();
}
String comparison: equals()
or ==
?
Let's look at an example.
String str1 = "Murzik";
String str2 = new String(str1);
boolean isCat = str1 == str2;
infoTextView.setText(str1 + " == " + str2 + " -> " + isCat);
Although the two variables contain the same word, we are dealing with two different objects and the operator
==
will return
false . Once, when the trees were large, I needed to compare two strings from different sources. Although the strings looked exactly the same, the comparison using the operator
==
returned
false and confused all the cards for me. And only then did I find out that I need to use the
equals()
. A string in Java is a separate object that may not be the same as another object, although the output of the string may look the same on screen. It’s just that Java, in the case of the logical operator
==
(as well as
!=
), compares references to objects (there is no such problem when working with primitives):
String s1 = "hello";
String s2 = "hello";
String s3 = s1;
String s4 = "h" + "e" + "l" + "l" + "o";
String s5 = new String("hello");
String s6 = new String(new char[]{'h', 'e', 'l', 'l', 'o'});
infoTextView.setText(s1 + " == " + s2 + ": " + (s1 == s2));
GO TO FULL VERSION