Строки Strings – это текстовые переменные. Здесь мы рассмотрим готовые функции пакета Java работы со строчными переменными в примерах и приведем часто используемые экранированные символы, таких как перевод каретки на новую строку, табуляция, обратный слеш и другие.
- Разбить строку — split()
// Разбить строку символом ,
String str = "This is a test text, for example";
String [] arr_str = str.split(",");
System.out.println(arr_str[0]);
/** This is a test text **/
// Разбить строку символом , или a
String [] arr_str2 = str.split(",|a");
System.out.println(arr_str2[1]);
/** test text **/
- Заменить текст — replaceAll()
// Заменить текст (, for) на :
String str = "This is a test text, for example";
String text = str.replaceAll(", for",":");
System.out.println(text);
/** This is a test text: example **/
- В нижний регистр — toLowerCase()
String str = "This is a test";
String text = str.toLowerCase();
System.out.println(text);
/** this is a test **/
- В верхний регистр — toUpperCase()
String str = "This is a test";
String text = str.toUpperCase();
System.out.println(text);
/** THIS IS A TEST **/
- Строка без начальных и конечных пробелов — trim()
String str = " This is a test ";
String text = str.trim();
System.out.println(text);
/**This is a test**/
- Обрезать строку — substring()
// С четвертого символа до конца
String str = "This is a test";
String text = str.substring(4);
System.out.println(text);
/**is a test**/
// От начала и до четвертого символа
String text2 = str.substring(0, 4);
System.out.println(text2);
/**This**/
- Поиск подстроки — contains()
String str = "This is a test";
Boolean find1 = str.contains("a");
Boolean find2 = str.contains("b");
System.out.println("A=" + find1 + ", B=" + find2);
/**A=true, B=false**/
- Позиция символа, подстроки — indexOf()
String str = "this is a test";
int index1 = str.indexOf("t");
int index2 = str.indexOf("t",1);
int index3 = str.indexOf("test");
System.out.println("index1=" + index1
+ ", index2=" + index2 + ", index3=" + index3);
/**index1=0, index2=10, index3=10**/
- Количество символов — length()
String str = "this is a test";
int size = str.length();
System.out.println(size);
/** 14 **/
- Сравнение строк игнорируя регистр — equalsIgnoreCase()
String str = "this is a test";
Boolean bool = str.equalsIgnoreCase("This is a Test");
System.out.println(bool);
/** true **/
- Сравнение строк — equals()
String str = "this is a test";
Boolean bool = str.equals("This is a Test");
System.out.println(bool);
/** false **/
- Экранированные символы строки Strings
\t
— Символ табуляции (в java – эквивалент четырех пробелов); \b
— Символ возврата в тексте на один шаг назад или удаление одного символа в строке (backspace); \n
— Символ перехода на новую строку; \r
— Символ возврата каретки; \f
— Прогон страницы к началу следующей страницы; \’
— Символ одинарной кавычки; \”
— Символ двойной кавычки; \\
— Символ обратной косой черты (\
).