Java string processing: substring, indexOf usage

Tip: After the article is written, the table of contents can be automatically generated. How to generate it can refer to the help document on the right


foreword

Manipulating strings is a common operation in Java. This article mainly introduces the usage of substring to partially intercept a string and the usage of indexOf to judge the position of a character in a string.


1. String interception: substring

The two commonly used methods are: substring(0,2) and substring(2)

1.String.substring(int start, int end)

substring(start,end) means only the beginning but not the end, so the interception is to intercept end-begin characters

For example: substring(0,2) is to intercept two characters, from the first to the second character, not including the third

String str = "hello world!";
System.out.println(str.substring(1, 4));
System.out.println(str.substring(3, 5));
System.out.println(str.substring(0, 4));

//输出结果为
ell
lo
hell

2.String.substring(int start)

The first explanation: start is the index of the position to start intercepting, the method will return a string, the content is the data between the start position of the original string and the end of the original string.

The second interpretation: it means to cut off the first start in the string to get the new string behind

For example: substring(2) intercepts all characters from the second position to the end of the string.
In other words: substring(2) is to intercept the first two characters of the string to get the new string behind

String str = "hello world!";
System.out.println(str.substring(1));
System.out.println(str.substring(3));
System.out.println(str.substring(6));

//输出结果为
ello world!
lo world!
world!

2. Get the character position: indexOf

Explanation: The indexOf() method is used to find a substring in an object of the String class. The method returns an integer value, which is the starting position of the substring. If there are multiple substrings, the integer value with the smallest value is returned; if not found substring, return -1

String str = "abcdefghijklmnabc";
System.out.println(str.indexOf("c")); //结果为2,为字符"c"第一次出现的位置
System.out.println(str.indexOf("x")); //结果为-1,没有找到字符"x"

//输出结果为
2
-1

Part of the content of this article is referenced from:
Two commonly used methods of substring
Usage of subString


Summarize

This article mainly introduces two commonly used methods in string processing: substring and indexOf.
I hope it will be useful to everyone!

Guess you like

Origin blog.csdn.net/qq_46119575/article/details/129633054