Java 字符串基本操作

news2024/10/7 13:19:33

一、Java 字符串比较

1、equals用法

String类覆盖了Object类的equals()方法,并提供了自己的实现,它根据它们的内容比较两个字符串的相等性。

equals() 方法用于将字符串与指定的对象比较。

语法

public boolean equals(Object anObject)

参数

  • anObject -- 与字符串进行比较的对象。

返回值

如果给定对象与字符串相等,则返回 true;否则返回 false。

示例:

比较两个字符串的相等性

String str1 = new String("Hello"); 
String str2 = new String("Hi"); 
String str3 = new String("Hello");

boolean b1,   b2;

b1  = str1.equals(str2); // false will be  assigned to b1 
b2  = str1.equals(str3); // true will be  assigned to b2

2、==用法

对于引用类型的变量来说,==比较的两个引用对象的地址是否相等。
==操作符总是比较内存中两个对象的引用。
str1 == str2和str1 == str3将返回false,因为str1,str2和str3是内存中三个不同String对象的引用。
对于基本类型变量来说,只能使用 == ,因为基本类型的变量没有方法。使用==比较是值比较。

二、比较

要根据字符的Unicode值比较两个字符串,请使用compareTo()方法。它的签名是

public int compareTo(String anotherString)

它返回一个整数,它可以是0(零),正整数或负整数。

该方法返回这两个字符的Unicode值之间的差异。

例如,“a”.compareTo(“b”)将返回-1。 Unicode的Unicode值为97,b为98。它返回差值97 - 98,它是-1。

以下是字符串比较的示例:

"abc".compareTo("abc") will  return  0
"abc".compareTo("xyz") will  return  -23  (value of  "a" -  "x") 
"xyz".compareTo("abc") will  return  23  (value of  "x" -  "a")

以下代码显示如何进行字符串比较。

public class Main {
  public static void main(String[] args) {
    String apple = new String("Apple");
    String orange = new String("Orange");
    System.out.println(apple.equals(orange));
    System.out.println(apple.equals(apple));
    System.out.println(apple == apple);
    System.out.println(apple == orange);
    System.out.println(apple.compareTo(apple));
    System.out.println(apple.compareTo(orange));
  }
}

上面的代码生成以下结果。

三、StringBuilder/StringBuffer

StringBuilder和StringBuffer是String类的伴随类。

它们表示一个可变的字符序列。

StringBuffer是线程安全的,StringBuilder不是线程安全的。

两个类都有相同的方法,除了StringBuffer中的所有方法都是同步的。

StringBuilder对象是可修改的字符串。 StringBuilder类包含四个构造函数:

StringBuilder()
StringBuilder(CharSequence seq)
StringBuilder(int capacity)
StringBuilder(String str)

no-args构造函数创建一个默认容量为16的空StringBuilder。

第二个构造函数使用CharSequence对象作为参数。

它创建一个StringBuilder对象,其内容与指定的CharSequence相同。

第三个构造函数使用int作为参数;它创建一个空的StringBuilder对象,其初始容量与指定的参数相同。

以下是创建StringBuilder对象的一些示例:

StringBuilder sb1  = new StringBuilder();
StringBuilder sb2  = new StringBuilder("Here is  the   content");
StringBuilder sb3  = new StringBuilder(200);

append()方法将文本添加到StringBuilder的结尾。它需要许多类型的参数。

insert()和delete()修改其内容。

1、长度和容量

StringBuilder类有两个属性:length和capacity。

它的长度是指其内容的长度,而其容量是指它可以容纳而不分配新的内存的最大字符数。

length()和capacity()方法分别返回其长度和容量。例如,

public class Main {
  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder(200); // Capacity:200, length:0
    sb.append("Hello"); // Capacity:200, length:5
    int len = sb.length(); // len is assigned 5
    int capacity = sb.capacity(); // capacity is assigned 200

  }
}

2、转换为字符串

我们可以通过使用其toString()方法将StringBuilder的内容作为String。

public class Main {
  public static void main(String[] args) {
    // Create a String object
    String s1 = new String("Hello");

    // Create a StringBuilder from of the String object s1
    StringBuilder sb = new StringBuilder(s1);

    // Append " Java" to the StringBuilder"s content
    sb.append(" Java"); // Now, sb contains "Hello Java"

    // Get a String from the StringBuilder
    String s2 = sb.toString(); // s2 contains "Hello Java"

  }
}

StringBuilder有一个setLength()方法,它的新长度作为参数。如果新长度大于旧长度,则额外位置用空字符填充(空字符为\ u0000)。

如果新长度小于旧长度,则其内容将被截断以适应新长度。

public class Main {
  public static void main(String[] args) {
    // Length is 5
    StringBuilder sb = new StringBuilder("Hello");

    // Now the length is 7 with last two characters as null character "\u0000"
    sb.setLength(7);

    // Now the length is 2 and the content is "He"
    sb.setLength(2);

  }
}

例子

StringBuilder类有一个reverse()方法,它用相同的字符序列替换其内容,但顺序相反。

以下代码显示了StringBuilder类的一些方法的使用。

public class Main {
  public static void main(String[] args) {
    // Create an empty StringBuffer
    StringBuilder sb = new StringBuilder();
    printDetails(sb);

    // Append "good"
    sb.append("good");
    printDetails(sb);

    // Insert "Hi " in the beginning
    sb.insert(0, "Hi ");
    printDetails(sb);

    // Delete the first o
    sb.deleteCharAt(1);
    printDetails(sb);

    // Append "  be  with  you"
    sb.append(" be  with  you");
    printDetails(sb);

    // Set the length to 3
    sb.setLength(3);
    printDetails(sb);

    // Reverse the content
    sb.reverse();
    printDetails(sb);
  }

  public static void printDetails(StringBuilder sb) {
    System.out.println("Content: \"" + sb + "\"");
    System.out.println("Length: " + sb.length());
    System.out.println("Capacity: " + sb.capacity());

    // Print an empty line to separate results
    System.out.println();
  }
}

上面的代码生成以下结果。

3、字符串连接运算符(+)

我们经常使用+运算符将字符串,原始类型值或对象连接到另一个字符串。

例如,

String str = "X" + "Y" + 12.56;

为了优化字符串连接操作,编译器用一个使用StringBuilder的语句替换字符串连接。

String str = new StringBuilder().append("X").append("Y").append(12.56).toString();

 四、Swtich用法

switch-expression使用String类型。如果switch-expression为null,则抛出NullPointerException。
case标签必须是字符串文字。我们不能在case标签中使用String变量。
以下是在switch语句中使用String的示例:

public class Main {
  public static void main(String[] args) {
    String status = "off";
    switch (status) {
    case "on":
      System.out.println("Turn on"); 
    case "off":
      System.out.println("Turn off");
      break;
    default:
      System.out.println("Unknown command");
      break;
    }
  }
}

五、字符串搜索

startsWith()检查字符串是否以指定的参数开头,而endsWith()检查字符串是否以指定的字符串参数结尾。两个方法都返回一个布尔值。

public class Main {
  public static void main(String[] args) {
    String str = "This is a test";

    // Test str, if it starts with "This"
    if (str.startsWith("This")) {
      System.out.println("String starts with  This");
    } else {
      System.out.println("String does  not  start with  This");
    }

    // Test str, if it ends with "program"
    if (str.endsWith("program")) {
      System.out.println("String ends  with  program");
    } else {
      System.out.println("String does  not  end  with  program");
    }

  }
}

我们可以使用indexOf()和lastIndexOf()方法获取另一个字符串中的字符或字符串的索引。例如:


public class Main {
  public static void main(String[] args) {
    String str = new String("Apple");

    int index = str.indexOf("p"); // index will have a value of 1
    System.out.println(index);
    
    index = str.indexOf("pl"); // index will have a value of 2
    System.out.println(index);
    index = str.lastIndexOf("p"); // index will have a value of 2
    System.out.println(index);
    
    index = str.lastIndexOf("pl"); // index will have a value of 2
    System.out.println(index);
    
    index = str.indexOf("k"); // index will have a value of -1
    System.out.println(index);
  }
}

indexOf()方法从字符串的开头开始搜索字符或字符串,并返回第一个匹配的索引。
lastIndexOf()方法从末尾匹配字符或字符串,并返回第一个匹配的索引。
如果在字符串中没有找到字符或字符串,这些方法返回-1。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/608628.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Dockerfile常用指令及其含义

编写dockerfile文件中常用指令: 指令说明FROM指明当前的镜像基于哪个镜像构建:LABEL标记镜像信息,添加元数据ARG定义构建镜像过程中使用的变量ENV指定环境变量VOLUME创建一个数据卷挂载点USER指定运行容器时的用户名或 UIDWORKDIR配置工作目录EXPOSE容器…

chatgpt赋能python:Python区分:为什么选择python?

Python区分:为什么选择python? Python是一种高级语言,一种功能强大且易于学习的编程语言。 它可用于各种领域,包括科学计算,Web开发和数据分析等。 Python的简单性和灵活性使其成为许多行业和开发者的首选编程语言。 …

R语言 tidyverse系列学习笔记(持续更新)

tidyverse 译 “洁净的宇宙” > “极乐净土” 以 iris 鸢尾花数据集为例 ** 查看数据集** ** 查看维度dimention** dim(iris)iris 数据集有150个对象(observation),5列 ( Sepal.Length , Sepal.Width , Petal.Length , Petal.Width , Spe…

大疆无人机 MobileSDK(遥控器/手机端)开发 v5版<2>

前言 v5.x版本的功能与v4.x基本相同,都是获取飞机的姿态信息、获取无人机多媒体文件、操作多媒体文件、航线规划等。不过在上一章节中也大致说了一些两个版本的中API的差别,下面是根据一些API使用所完成的一些功能,因为项目原因只能提供部分代码供参考,后续如果有这方面需…

零基础开发小程序第五课-修改数据

目录 1 创建修改页面2 创建远程数据3 给组件绑定默认值4 从详情页跳转到更新页5 刷新页面总结 新手开发往往对修改和删除的功能不是特别理解。我们先按照开发的思路捋一下逻辑,如果想修改数据,首先需要知道修改哪一条数据,然后要把上一次存储…

DINO代码学习笔记(一)

先上官方架构图: 论文地址:https://arxiv.org/pdf/2203.03605.pdf 代码地址:GitHub - IDEA-Research/DINO: [ICLR 2023] Official implementation of the paper "DINO: DETR with Improved DeNoising Anchor Boxes for End-to-End Objec…

什么是数据可视化测试?

在我们日益由数据驱动的世界中,拥有可访问的方式来查看和理解数据比以往任何时候都更加重要。毕竟,员工对数据技能的需求每年都在稳步增长。各级员工和企业主都需要了解数据及其影响。 这就是数据可视化派上用场的地方。为了使数据更易于访问和理解&…

在nodejs addon 环境下抓视频和音频数据包

在node addon 环境下开发音视频,需要用到 gyp 。这个配置比较简单,很快可以配置好。比较坑的是,在vscode 开发环境下, 如果装了conda 或者 mini conda . 有可能会影响gpy程序的编译。谨慎起见,可以看看控制台是否有 …

好物周刊#2:AI 写作助手

不要哀求,学会争取。若是如此,终有所获。 🎈 项目 vue-fabric-editor 基于 fabric.js 和 Vue 的图片编辑器,可自定义字体、素材、设计模板。 目前已支持以下功能: 导入 JSON 文件保存为 PNG、SVG、JSON 文件插入 S…

我与 INDCODE AI 创作助手的一次对话

本文由 大侠(AhcaoZhu)原创,转载请声明。 链接: https://blog.csdn.net/Ahcao2008 我与INDCODE AI 创作助手的一次对话 🧊摘要🧊前言🧊对话内容🧊结束语 🧊摘要 本文介绍了 CSDN 嵌入式INSCODE AI 创作助手…

msvcr120.dll丢失怎样修复

MSVCR120.dll是Windows操作系统上一个非常重要的动态链接库文件,它包含了一些运行时库函数,被许多应用程序用来进行编译和运行。如果该文件丢失或损坏,很多应用程序就无法正常运行,这可能会带来一些麻烦。本篇文章将详细介绍MSVCR…

FAT32文件系统详解

FAT32文件系统详细分析 (续FAT文件系统详解) 文章目录 FAT32文件系统详细分析 (续FAT文件系统详解)1. 前言2. 格式化SD nand/SD卡3. FAT32文件系统分析3.1 保留区分析3.1.1 BPB(BIOS Parameter Block) 及BS区分析3.1.2 FSInfo 结构…

SpringCloud_微服务基础day1(走进微服务,认识springcloud,微服务(图书管理)项目搭建(一))

官方网站:柏码 - 让每一行代码都闪耀智慧的光芒! (itbaima.net) p1:前言,走进微服务 注意:此阶段学习推荐的电脑配置,至少配备4核心CPU(主频3.0Ghz以上)16GB内存,否则卡到你怀疑人生…

【CH32V】CH32V307驱动4P_OLED

前言 手上正好有 CH32V307 的板子就耍耍,网上4P的OLED例程也不少 4P OLED 屏驱动例程。在加上一些 STM32 标准库的知识,改改引脚定义,就可以将 OLED 屏连接到板子上进行显示了。当然,我也将会分享我整理好的库文件代码和完整的工程…

【22】SCI易中期刊推荐——计算机 | 人工智能(中科院4区)

🍀🍀>>>【YOLO魔法搭配&论文投稿咨询】<<<🍀🍀 ✨✨>>>学习交流 | 温澜潮生 | 合作共赢 | 共同进步<<<✨✨ 📚📚>>>人工智能 | 计算机视觉 | 深度学习Tricks | 第一时间送达<<<📚📚 🚀🚀🚀…

【java 基础二 】- 面向对象、类、接口等

一、定义 Java面向对象编程(OOP)是一种编程范式&#xff0c;其旨在通过将程序逻辑封装在对象中来使代码更易于理解和维护。Java是一种面向对象的编程语言&#xff0c;它支持封装、继承和多态等概念。以下是Java面向对象编程的核心概念&#xff1a; 对象(Object)&#xff1a;对…

BM7 算法

描述 给一个长度为n链表&#xff0c;若其中包含环&#xff0c;请找出该链表的环的入口结点&#xff0c;否则&#xff0c;返回null。 数据范围&#xff1a; n≤10000n≤10000&#xff0c;1<结点值<100001<结点值<10000 要求&#xff1a;空间复杂度 O(1)O(1)&#x…

Linux进程间通信——管道,共享内存,消息队列,信号量

进程间通信 文章目录 进程间通信进程间通信的方式进程间通信的概念如何实现进程间通信管道什么是管道 进程间怎么通信 匿名管道pipe函数创建管道通信读写特征写慢读快写快读慢写端关闭&#xff0c;读端读完读端关闭&#xff0c;写端&#xff1f; 管道特征 命名管道命名管道特性…

近期学习论文总结 2

公众号&#xff1a;EDPJ 目录 0. 摘要 1. Artificial Fingerprinting for Generative Models: Rooting Deepfake Attribution in Training Data 1.1 核心思想 1.2 步骤 2. HyperDomainNet: Universal Domain Adaptation for Generative Adversarial Networks 2.1 核心思想…

使用Chat gpt提高Android开发效率

简介 在过去几周里&#xff0c;我进行了一项令人大开眼界的实验&#xff0c;将 Chat-GPT&#xff08;我使用的是 Bing Chat&#xff0c;它在后台使用了 GPT-4&#xff0c;并且可以免费使用&#xff09;融入到我的日常 Android 开发工作流程中&#xff0c;以探索它是否能够提高…