search
HomeJavajavaTutorialUsage examples of important methods of java string

The String class will be one of your main tools for storing and processing languages. This article will lead you to have a basic understanding of Java string methods and understand how to use its functions.

Usage examples of important methods of java string

1. Return String "length" method

How do you determine the length of a given String? Java provides a method called "length()". Use it for when you need to find the length of a String.

public class Str_Sample {
	public static void main(String[] args){
		//测试String长度的方法
		String name="hello work";
		//length方法返回的是整数
		int num=name.length();
		System.out.println("字符串的长度:"+num);
	}
}

Run the above example, the output is as follows:

字符串长度:10

2. String "indexOf()" method

How can I find which character is in which position?

"indexOf" can help you specify the position where a specific character first appears. If it cannot be found, it returns -1

public class Str_Sample{
    public static void main(String[] args){
       String name="I like java. How do you like java?";
	   int num=name.indexOf("java");
	   System.out.println("java第一次出现的位置:"+num);
    }
}

Run the above example, the output result is as follows:

java第一次出现的位置:7

3. String "lastindexOf()" method

If I know the length, where do I want to find the character from the back of the string?

"lastindexOf" can start the reverse search from the specified position and return the position where the specific character you specified last appears. If it cannot find it, it will return -1

public class Str_Sample{
    public static void main(String[] args){
        String name="I like java. How do you like java?";
        //name的长度
        int num=name.length();
	        //lastindexOf(指定特殊字符,指定位置)
              int index=name.lastindexOf("java",num);
                System.out.println("java最后一次出现的位置:"+index);
	     
    }
]

Run the above example, the output result is as follows :

java最后一次出现的位置:29

4. String "substring()" method

What should I do if I only want a section of the string?

"subString" can intercept the string from the specified header and return the intercepted string. Note: The range expressed in Java includes the head but not the tail.

public class Str_Sample{
    public static void main(String[] args){
        String name="I like java. How do you like java?";
        //截取How这个字母,首先你要知道H的下标,可使用之前的indexOf方法
        int num=name.indexOf("H");
        //由于java中示范围都是含头不含尾,所以要多加一位
        String str=name.substring(num,num+3);
        System.out.println(str);
        //也可从指定位置直接截取到字符串尾部
        String str2=name.substring(num);
        System.out.println(str2);
    }
]

Run the above example, the output result is as follows:

How
How do you like java?

5. String "charAt()" method

How can I get characters based on position?

"chatAt" can help you, used to return the character of the specified subscript

public class Str_Sample{
    public static void main(String[] args){
        String name="I like java. How do you like java?";
        //创建循环遍历name的下标
        for(int i=0;i<name.length><p>Run the above example, the output result is as follows: </p>
<pre class="brush:php;toolbar:false">I like java. How do you like java?

6. String "startsWith( ), endsWith()" method

How to determine what the string begins or ends with?

"startsWith()", checks whether the string starts with the specified string. "endsWith()" checks whether the string ends with the specified string

public class Str_Sample{
    public static void main(String[] args){
        String name="I like java. How do you like java?";
        //是否以“I”开头,正确返回true,否则返回false
        boolean s1=name.startsWith("I");
        //startsWith()第二种用法,可判断指定位置是否是指定字符串
        boolean s2=name.startsWith("java",7);
        //判断字符串是否以“?”结尾
        boolean e1=name.endsWith("?");
        System.out.println("是否以“I”开头:"+s1);    
        System.out.println("位置7是否是“java”开头:"+s2);
        System.out.println("是否以“?”结尾:"+e1);
      }
}

Run the above example, the output result is as follows:

否以“I”开头:true
位置7是否是“java”开头:true
是否以“?”结尾:true

7. String "compareTo()"Method

"compareTO" It starts the comparison from the first character. If it encounters different characters, it immediately returns the difference in the ascii value of the two characters. The return value is int type .

public class Str_Sample{
    public static void main(String[] args){
        //A的ascli值为65,a的ascli值为97
        String a="A";
        String b="a";
        String c="aa";
        String d="abc";
        String e="ad";
        int num=a.compareTo(b);
        //还有一种方法忽略大小写进行比较
        int num2=a.compareToIgnoreCase(b);
        //长度不一样且前几个字符也不一样,从第一位开始找,当找到不一样的字符时,则返回的值是这两个字符比较的值
        int num3=c.compareTo(d);
        //如多个字符,第一个字符相同则直接比较第二个字符,以此类推
        int num4=e.compareTo(c);
        System.out.println("a与b比较:"+num);
        System.out.println("a与b比较(忽略大小写):"+num2);
        System.out.println("c与d比较:"+num3);
        System.out.println("e与d比较:"+num4);
     }
}

Run the above example, the output result is as follows:

a与b比较:-32
a与b比较(忽略大小写):0
c与d比较:-1
e与d比较:3

8. String "contains()"Method

What if you want to know if a string contains the string you want?

Then "contanins" can meet your needs to determine whether it contains the specified string

public class Str_Sample{
    public static void main(String[] args){
        String name="I like java. How do you like java?";
        //判断是否包含“you”这个字符串
        boolean bl=name.contains("you");
        System.out.println("name字符串中是否包含“you”:"+bl);
    }
]

Run the above example, the output results are as follows:

name字符串中是否包含“you”:true

9.字符串“replace()”方法

您可以指定要替换的字符串部分以及参数中的替换字符串。

public class Str_Sample{
    public static void main(String[] args){
        String name="I like java. How do you like java?";
        String str=name.replace("java", "php");
        System.out.println("替换前:"+name);
        System.out.println("替换后:"+str);
    }
]

运行以上实例,输出结果如下:

替换前:I like java. How do you like java?
替换后:I like php. How do you like php?

10.字符串“toLowerCase()”和“toUpperCase()”方法

“toLowerCase()”将字符串以小写形式显示,toUpperCase()”将字符串以大写形式显示。

public class Str_Sample{
    public static void main(String[] args){
        String name="I like java. How do you like Java?";
        String low=name.toLowerCase();
	    String upp=name.toUpperCase();
        System.out.println("小写显示:"+low);
        System.out.println("大写显示:"+upp);
    }
]

运行以上实例,输出结果如下:

小写显示:i like java. how do you like java?
大写显示:I LIKE JAVA. HOW DO YOU LIKE JAVA?

本篇文章到这里就已经全部结束了,如有不足之处请见谅,更多其他精彩内容可以关注PHP中文网的Java视频教程栏目!

The above is the detailed content of Usage examples of important methods of java string. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor