本篇文章给大家带来的内容是关于Java中String字符串运算的介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
一、字符串运算 String类
1、概述
String是特殊的引用数据类型,它是final类。
2.构造方法
String str = "abc";
相当于: char date[] = {'a','b','c'};
String str = new String{data};
3.主要方法
char charAt(int index) 返回char指定索引处的值。
boolean contains(CharSequence s)当且仅当字符串包含指定char值序列返回true
boolean equals(Object anObject) 将次字符串与指定对象进行比较
int indexOf(int ch) 返回指定字符第一次出现的索引值
int length() 返回字符串的长度,多用于循环的终止条件
boolean matches(String regex) 判断一个字符串是否匹配给定的规则表达式
String replace(char oldChar,char newChar) 将串中所有的oldChar替换为newChar
String split(String regex) 将字符串按照规矩进行切分
String subString(int beginIndex) 返回该字符串的beginindex索引之后的字符串
String toLowerCase() 将该字符串中的所有大写字母变为小写字母
String toUpperCase() 将该字符串中的所有小写字母变为大写字母
String trim() 删除该字符串所有前导和尾随的空格并返回
/*类型转换*/
static String valueOf(boolean b)
返回 boolean参数的字符串 boolean形式。
static String valueOf(char c)
返回 char参数的字符串 char形式。
static String valueOf(char[] data)
返回 char数组参数的字符串 char形式。
static String valueOf(char[] data, int offset, int count)
返回 char数组参数的特定子阵列的字符串 char形式。
static String valueOf(double d)
返回 double参数的字符串 double形式。
static String valueOf(float f)
返回 float参数的字符串 float形式。
static String valueOf(int i)
返回 int参数的字符串 int形式。
static String valueOf(long l)
返回 long参数的字符串 long形式。
static String valueOf(Object obj)
返回 Object参数的字符串 Object形式。
注意:String字符串“==”与equals方法的区别:
如果是通过String str = ""声明的,==和equals都可是使用;
如果是通过new String ("")声明的,不能用==,只能用equals。
4.演示案例
需求一:计算一个字符串中大写字母、小写字母和数字的个数
思路:将字符串通过for循环进行便利,使用charAt方法获取每一位字符,然后将每一位字符与AscII码对应的值相对比判断是大写字母、小写字母、数字,计数打印。
/** * @ author: PrincessHug * @ date: 2019/2/7, 17:09 * @ Blog: https://www.cnblogs.com/HelloBigTable/ */ public class StringAPIDemo { /** * 需求:计算字符串中大写字母、小写字母、数字出现的次数 * @param args 参数 */ public static void main(String[] args) { //通过用户输入得到一个字符串 String str = getString(); getCount(str); } private static void getCount(String str) { int upperNum = 0; int lowerNum = 0; int digit = 0; for (int i = 0;i< str.length();i++){ char c = str.charAt(i); /** * AscII码数字1-9(48-57),A-Z(65-91),a-z(97-123) */ if (c>=48 && c<=57){ digit++; } if (c>=65 && c<=91){ upperNum++; } if (c>=97 && c<=123){ lowerNum++; } } System.out.println("数字出现的次数为:" + digit); System.out.println("大写字母出现的次数为:" + upperNum); System.out.println("小写字母出现的次数为:" + lowerNum); } private static String getString() { System.out.println("请输入一个字符串:"); Scanner scanner = new Scanner(System.in); String s = scanner.nextLine(); return s; } }
需求二:查询父字符串中某一个子字符串出现的次数
思路1:使用indexOf方法查询子字符串第一次出现的索引a,再使用subString方法返回父字符串索引(a+子字符串长度)之后的字符串,并计数+1,循环该操作知道indexOf方法返回值为-1停止,获取计数值即可。
思路2:使用split方法将父字符串按照子字符串进行切分得到String数组,使用subString方法获取父字符串最后的字符串是否等于子字符串,若等于,返回String数组的length长度;若不等,则返回String数组的length-1.
** * @ author: PrincessHug * @ date: 2019/2/7, 17:34 * @ Blog: https://www.cnblogs.com/HelloBigTable/ */ public class FindChildStringCount { /** * 需求:查询父字符串中某一个子字符串的数量 * @param args */ public static void main(String[] args) { String parent = "itstar123qweritstar()%%dfitstarsdgji"; String child = "itstar"; int num1 = getChildStringCount01(parent, child); int num2 = getChildStringCount02(parent,child); int num3 = getChildStringCount03(parent,child); System.out.println("方法一:" + num1 + "次。"); System.out.println("方法二:" + num2 + "次。"); System.out.println("方法三:" + num3 + "次。"); } private static int getChildStringCount02(String parent, String child) { String[] s = parent.split(child); if (child.equals(parent.substring(parent.length()-child.length()))){ return s.length; }else { return s.length-1; } } private static int getChildStringCount01(String parent,String child) { int num = 0; int index = 0; while ((index = parent.indexOf(child)) != -1){ num++; parent = parent.substring(index + child.length()); } return num; } private static int getChildStringCount03(String parent,String child){ String[] s = parent.split(child); int sum = 0; for (int i = 0;i < s.length;i++){ sum += s[i].length(); } return sum==parent.length()-(s.length-1)*child.length()?s.length-1:s.length; } }
5.String的规则匹配(正则表达式)
正则表达式常用于验证身份证号、qq号、邮箱等
字符类及含义:
[abc] => abc都可以
[a-zA-Z] => a-z或者A-Z都可以,两头都是闭区间
[0-9] => 数字0-9都可以
\d => 与[0-9]一样
\D => 不能是数字
\w => 表示字母、数字、下划线都可以,等于[a-zA-Z0-9_]
x? => 表示x出现一次或一次也没有
x* => 表示x出现了零次或多次
X{n} => 表示x出现了n次
X{n,m} => 表示x出现了n到m次
X+ => 表示x至少出现了一次
^ => 表示正则表达式的开头
& => 表示正则表达式结尾
需求一:验证qq号码是否正确
qq号码条件:
(1)位数为5-15位
(2)开头数字不能为0
正则表达式为:regex = [1-9]\\d{4-14}
需求二:验证手机号码是否正确
手机号条件:
(1)位数为11位
(2)第一位为1
(3)第二位为3-9
正则表达式为:regex = [1]][3-9]\\d{9}
需求三:验证邮箱是否正确
邮箱条件:
(1)@之前为邮箱名,字母、数字、下划线都可以
(2)@符号
(3)@之后为邮箱域名(qq.com/163.com.cn)
正则表达式为:regex = \\w+@[a-zA-Z0-9]+(\\.\\w{2,3})+
以下为需求一:验证qq号码是否正确,需求二、三只需将regex修改为对应的正则表达式即可。
/** * @ author: PrincessHug * @ date: 2019/2/7, 21:51 * @ Blog: https://www.cnblogs.com/HelloBigTable/ */ public class MatchQQ { public static void main(String[] args) { while (true) { String qq = getQQ(); if (qq.equals("stop")){ break; }else { matchQQ(qq); } } } /** * @return 返回获取的qq号 */ private static String getQQ() { Scanner sc = new Scanner(System.in); System.out.println("请输入您的qq号"); String s = sc.nextLine(); return s; } /** * 验证qq号是否匹配regex表达式 * @param qq 获得用户输入的qq号 */ private static void matchQQ(String qq) { String regex = qqRegex(); if (qq.matches(regex)) { System.out.println("QQ号正确!"); } else { System.out.println("QQ号错误!"); } } /** * @return 返回qq的正则表达式 */ private static String qqRegex() { String regex = "[1-9][0-9]{4,14}"; return regex; } }
以上是Java中String字符串运算的介绍(代码示例)的详细内容。更多信息请关注PHP中文网其他相关文章!

JVM'SperformanceIsCompetitiveWithOtherRuntimes,operingabalanceOfspeed,安全性和生产性。1)JVMUSESJITCOMPILATIONFORDYNAMICOPTIMIZAIZATIONS.2)c提供NativePernativePerformanceButlanceButlactsjvm'ssafetyFeatures.3)

JavaachievesPlatFormIndependencEthroughTheJavavIrtualMachine(JVM),允许CodeTorunonAnyPlatFormWithAjvm.1)codeisscompiledIntobytecode,notmachine-specificodificcode.2)bytecodeisisteredbytheybytheybytheybythejvm,enablingcross-platerssectectectectectross-eenablingcrossectectectectectection.2)

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java实现“一次编写,到处运行”通过编译成字节码并在Java虚拟机(JVM)上运行。1)编写Java代码并编译成字节码。2)字节码在任何安装了JVM的平台上运行。3)使用Java原生接口(JNI)处理平台特定功能。尽管存在挑战,如JVM一致性和平台特定库的使用,但WORA大大提高了开发效率和部署灵活性。

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允许Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

JavaispoperfulduetoitsplatFormitiondence,对象与偏见,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

Java的顶级功能包括:1)面向对象编程,支持多态性,提升代码的灵活性和可维护性;2)异常处理机制,通过try-catch-finally块提高代码的鲁棒性;3)垃圾回收,简化内存管理;4)泛型,增强类型安全性;5)ambda表达式和函数式编程,使代码更简洁和表达性强;6)丰富的标准库,提供优化过的数据结构和算法。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

禅工作室 13.0.1
功能强大的PHP集成开发环境

SublimeText3 Linux新版
SublimeText3 Linux最新版

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

MinGW - 适用于 Windows 的极简 GNU
这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中