Java 字符串:在 Java 中使用字符串

作者 : 慕源网 本文共4313个字,预计阅读时间需要11分钟 发布时间: 2022-04-9 共395人阅读

字符串在 Java 中非常易于使用。需要注意的主要事情是使用+附加到字符串操作员效率不高;它不必要地创建了新的字符串对象。对于大多数程序来说,这并不重要。但是,如果您正在处理大量

字符串并且速度是一个问题,请使用StringBuffer(线程安全)或StringBuilder(不是线程安全但效率稍高一些)。

另请注意,Java 并不是世界上处理大量文本数据最有效的语言。Perl 或 Python 脚本的运行速度通常比 Java 文本处理程序快得多。

最后,不要忘记使用.equals()来比较字符串中的文本,而不是 == (比较对象,而不是文本)。

在 Java 中声明和初始化字符串

您可以使用String类 在 Java 中声明和初始化字符串。

String text = "Hello";
System.out.println(text);
Hello

在 Java 中加入、连接或附加字符串

在 Java 中连接字符串的最简单方法是使用+。这就像你期望的那样工作。

String text1 = "Hello";
String text2 = "Jim";
        
System.out.println(text1 + " " + text2);
Hello Jim

但是,这不是很有效,因为每次编写+时,都会创建一个新的 String 对象。出于这个原因,您可能更喜欢使用StringBuilder或旧的线程安全版本StringBuffer

 

StringBuilder sb = new StringBuilder();
        
sb.append("Hello");
sb.append(" to");
sb.append(" you");
        
System.out.println(sb.toString());
Hello to you

更好的是,由于append()返回对 StringBuilder 对象本身的引用,我们可以这样写,效果相同:

 

StringBuilder sb = new StringBuilder();
        
sb.append("Hello")
.append(" to")
.append(" you");
        
System.out.println(sb.toString());

Java 子字符串:在 Java 中选择部分字符串

您可以使用substring方法 在 Java 中获取字符串的一部分。

String substring(int beginIndex, int endIndex)

这里的endIndex是可选的;如果省略,您将获得 beginIndex 之后的整个字符串。请注意,您选择的子字符串不包括 endIndex 本身的字符。它包括直到endIndex 的所有字符。

所选子串的长度为 endIndex – startIndex。

这里有些例子。

String text = "The quick brown fox";
        
// Everything from index 4 onwards
System.out.println(text.substring(4));
        
// Index 0 up to but not including index 3.
System.out.println(text.substring(0, 3));
quick brown fox
The

Java 数组字符串:连接字符串数组

令人惊讶的是,在核心 Java 中似乎没有连接字符串数组的方法,尽管这些方法存在于各种库中。你总是可以自己动手。下面的类声明了这样一个方法,并使用它来连接一个字符串数组。您可以轻

松地调整它以使用 ArrayList 或 Vector 或其他任何东西。

package caveofprogramming.aquarium;

import java.util.*;

public class Test {
    public static String join(String[] strings, String glue) {
    
        StringBuilder sb = new StringBuilder();
        
        for(int i=0; i < strings.length; i++) {
            sb.append(strings[i]);
            
            if(i < strings.length - 1) {
                sb.append(glue);
            }
        }
        
        return sb.toString();
    }
    
    public static void main(String [] args) {

        String texts[] = {"Hello", "to", "you"};
        System.out.println(join(texts, " "));
    }
}
Hello to you

Java 字符串拆分:将字符串拆分为标记

您可以使用split(REGEX)方法 将字符串拆分为标记数组。

让我们看一些例子。

在空格上拆分(这也适用于制表符):

String text = "The quick brown fox";
        
// Split on whitespace
String [] tokens = text.split("\s+");
        
for(int i=0; i < tokens.length; i++) {
    System.out.println(tokens[i]);
}
The
quick
brown
fox

将电子邮件地址拆分为多个部分:

String text = "someone@nowhere.com";

// Split on @ and .
// The double backslashes make this regular
// expression look more confusing than it is.
// We are escaping once for the sake of the
// regex, and again for the sake of Java.
String [] tokens = text.split("[\@\.]+");

for(int i=0; i < tokens.length; i++) {
    System.out.println(tokens[i]);
}
someone
nowhere
com

Java 字符串比较:比较 Java 中的字符串

要在 java 中比较字符串,请使用.equals,而不是 ==。

== 会告诉你两个引用是否指向同一个对象。要测试两个字符串是否相同, .equals 可以满足您的要求。

下面的程序说明了这一点。

// Here's some text.
String text1 = "Hello there";

// Here's the same text.
String text2 = "Hello there";

// Here's a second reference to the 
// first string.
String text3 = text1;

// The first two strings are equal
// (contain the same text)
if(text1.equals(text2)) {
    System.out.println("text1 matches text2.");
}

// ... and in this case they are the same object, 
// which presumably is due to optimization by the
// virtual machine. DO NOT rely on this!!
if(text1 == text2) {
    System.out.println("text1 and text2 are the same object (oddly)");
}

// text2 and text3 ARE clearly the same object, however.
if(text2 == text3) {
    System.out.println("text2 and text3 are the same object.");
}
text1 matches text2.
text1 and text2 are the same object (oddly)
text2 and text3 are the same object.

Java 是字符串:如何判断对象是否为字符串

要检查对象是否为字符串,请使用instanceof

// Here's a string.
String text1 = "Hello there";

if(text1 instanceof java.lang.String) {
    System.out.println("It's a string!");
}
It's a string!

Java 字符串格式:格式化字符串或将数字转换为字符串

如果您只想在 Java 中将数字转换为字符串,使用toString()非常容易。您可能必须首先将原始类型(如int )包装在IntegerDouble类型的对象中。

// An int.
int count = 59;

// A float.
double cost = 57.59;

// Convert int to string and display.
System.out.println(new Integer(count).toString());

// Convert float to string and display.
System.out.println(new Double(cost).toString());
59
57.59

如果您想更好地控制数字的格式,则需要静态format()方法。

这个方法的工作原理很像 C 或 Perl 中的 sprintf。这是一个格式化各种数字的示例。

// An int.
int count = 59;

// A float.
double cost = 57.59;

// Format the numbers together with some text.
// For 'cost', we make the entire number 7 characters
// wide (including the .); we left-pad with zeros
// and put two numbers after the decimal point.
String text = String.format("Count: %d, Cost: $%07.2f", 
    count, cost);

System.out.println(text);
Count: 59, Cost: $057.59

Java Cast String:从其他对象创建字符串

不要忘记,任何时候你想在java中将一个对象变成一个字符串,只需使用对象的toString()方法。

如果一个不存在,或者它没有做你想要的,考虑覆盖它。

强烈推荐

海量程序代码,编程资源,无论你是小白还是大神研究借鉴别人优秀的源码产品学习成熟的专业技术强势助力帮你提高技巧与技能。在此处获取,给你一个全面升级的机会。只有你更值钱,才能更赚钱

如果你是初级程序员可以研究别人的代码提高技术,如果你喜欢搞网盟或者外包,可以让你快速建站,还等什么赶快关注吧,我们会持续输出相关资源

海量源码程序,学习别人的产品设计思维与技术实践


慕源网 » Java 字符串:在 Java 中使用字符串

常见问题FAQ

程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!

发表评论

开通VIP 享更多特权,建议使用QQ登录