当前位置: 首页 > news >正文

由LeetCode541引发的java数组和字符串的转换问题

起因是今天在刷下面这个力扣题时的一个报错

541. 反转字符串 II - 力扣(LeetCode)

这个题目本身是比较简单的,所以就不讲具体思路了。问题出在最后方法的返回值处,要将字符数组转化为字符串,第一次写的时候也没思考直接就是return charArray.toString()

class Solution {public String reverseStr(String s, int k) {int len=s.length();char[] charArray = s.toCharArray();for (int i = 0; i < s.length()-1; i+=2*k) {int start=i;//这里是判断尾数够不够k个来取决end指针的位置int end=Math.min(charArray.length-1,start+k-1);while (start<end){char temp=charArray[start];charArray[start]=charArray[end];charArray[end]=temp;start++;end--;}}return charArray.toString();
}
}

然后就出现了以下报错:

发现输出竟然是一坨看不懂的东西

后面思考了一下,原因如下:

toString()是顶级父类object中的方法,数组类中并没有对此方法重写(override),仅仅是重载(overload)为类的静态方法。所以,数组直接使用toString(),会去调用object类里面的toString方法,结果是[类型@哈希值]。

于是后面我又用了return Arrays.toString(charArray)还是不行。

class Solution {public String reverseStr(String s, int k) {int len=s.length();char[] charArray = s.toCharArray();for (int i = 0; i < s.length()-1; i+=2*k) {int start=i;//这里是判断尾数够不够k个来取决end指针的位置int end=Math.min(charArray.length-1,start+k-1);while (start<end){char temp=charArray[start];charArray[start]=charArray[end];charArray[end]=temp;start++;end--;}}return Arrays.toString(charArray);}
}

原来Arrays.toString(charArray)得到的字符串输出是有格式的而题目要求直接输出字符串。

最后用的是return new String(charArray);终于是通过了。

class Solution {public String reverseStr(String s, int k) {int len=s.length();char[] charArray = s.toCharArray();for (int i = 0; i < s.length()-1; i+=2*k) {int start=i;//这里是判断尾数够不够k个来取决end指针的位置int end=Math.min(charArray.length-1,start+k-1);while (start<end){char temp=charArray[start];charArray[start]=charArray[end];charArray[end]=temp;start++;end--;}}return new String(charArray);}
}

通过这次刷题,我也发现了我对Java 数组和字符串的转换这方面非常不熟悉,于是就总结了一下这方面的内容

java数组->字符串


       java中所有的类,不管是java库里面的类,或者是你自己创建的类,全部是从object这个类继承的。object里有一个方法就是toString(),那么所有的类创建的时候,都有一个toString的方法。这个方法是干什么的呢?

首先我们得了解,java输出用的函数print();是不接受对象直接输出的,只接受字符串或者数字之类的输出。

Object类中的toString()方法的源代码如下:

    /*** Returns a string representation of the object. In general, the* {@code toString} method returns a string that* "textually represents" this object. The result should* be a concise but informative representation that is easy for a* person to read.* It is recommended that all subclasses override this method.* <p>* The {@code toString} method for class {@code Object}* returns a string consisting of the name of the class of which the* object is an instance, the at-sign character `{@code @}', and* the unsigned hexadecimal representation of the hash code of the* object. In other words, this method returns a string equal to the* value of:* <blockquote>* <pre>* getClass().getName() + '@' + Integer.toHexString(hashCode())* </pre></blockquote>** @return  a string representation of the object.*/public String toString() {return getClass().getName() + "@" + Integer.toHexString(hashCode());}

char[] data = {'a', 'b', 'c'};
System.out.println(data.toString());  //输出结果为[C@79fc7299


输出会去调用object类里面的toString 方法,根据源码可知,输出结果为[类型@哈希值]
数组类中并没有对此方法重写(override),仅仅是重载(overload)为类的静态方法(参见java.util.Arrays)。

所以,数组直接使用toString(),会去调用object类里面的toString方法,结果是[类型@哈希值]。

数组转字符串可以使用Arrays类中的toString方法Arrays.toString(data)。附上Arrays类的toString方法源码。但是由源码可知,这种方法的toString()是带格式的,也就是说输出的是[a, b, c]。

 /*** Returns a string representation of the contents of the specified array.* The string representation consists of a list of the array's elements,* enclosed in square brackets (<tt>"[]"</tt>).  Adjacent elements are* separated by the characters <tt>", "</tt> (a comma followed by a* space).  Elements are converted to strings as by* <tt>String.valueOf(char)</tt>.  Returns <tt>"null"</tt> if <tt>a</tt>* is <tt>null</tt>.** @param a the array whose string representation to return* @return a string representation of <tt>a</tt>* @since 1.5*/public static String toString(char[] a) {if (a == null)return "null";int iMax = a.length - 1;if (iMax == -1)return "[]";StringBuilder b = new StringBuilder();b.append('[');for (int i = 0; ; i++) {b.append(a[i]);if (i == iMax)return b.append(']').toString();b.append(", ");}}


如果仅仅想输出abc则需用以下两种方法:


  直接在构造String时转换。

        char[] data = {'a', 'b', 'c'};String str = new String(data);


 调用String类的方法转换。

        String.valueOf(data)


String类valueOf方法的源码如下,由源码可知,valueOf实际也是new String对象,和方法1一样。

/*** Returns the string representation of the <code>char</code> array* argument. The contents of the character array are copied; subsequent* modification of the character array does not affect the newly* created string.** @param   data   a <code>char</code> array.* @return  a newly allocated string representing the same sequence of*          characters contained in the character array argument.*/public static String valueOf(char data[]) {return new String(data);}


java字符串->数组

toCharArray() 方法

示例如下:

String str = "Hello, world!";
char[] charArray = str.toCharArray();
System.out.println(Arrays.toString(charArray));

http://www.lryc.cn/news/302562.html

相关文章:

  • HTTP 头部- Origin Referer
  • Python 实现Excel 文件合并
  • ECMAScript 6+ 新特性 ( 一 )
  • 动态DP入门线性动态DP
  • 基于python+django+vue.js开发的停车管理系统
  • 网站管理新利器:免费在线生成 robots.txt 文件!
  • 【Java程序员面试专栏 Java领域】Java虚拟机 核心面试指引
  • 洛谷C++简单题小练习day15—计算阶乘小程序(不用循环)
  • Vue报错,xxx is defined #变量未定义
  • Idea启动Gradle报错: Please, re-import the Gradle project and try again
  • Python函数(一)
  • Excel表的内容批量生成个人加水印的Word文档
  • 微服务设计:Spring Cloud API 网关概述
  • stm32学习笔记-STLINK使用
  • Linux CentOS stream 9 firewalld
  • VLM多模态图像识别小模型UForm
  • 我的NPI项目之设备系统启动(七) -- 高通OS启动阶段和镜像分区简析
  • vue框架-vue-cli
  • Sora (text-to-video model-文本转视频模型)
  • java生态环境评价Myeclipse开发mysql数据库web结构java编程计算机网页项目
  • 数据结构-最短路径(Dijkstra算法与Floyd算法)
  • 文献速递:GAN医学影像合成--联邦生成对抗网络基础医学图像合成中的后门攻击与防御
  • Java实现自动化pdf打水印小项目 使用技术pdfbox、Documents4j
  • hive load data未正确读取到日期
  • C++ 遍历map的3中方法
  • redis 主从模式,sentinel 模式配置
  • 小型医院医疗设备管理系统|基于springboot小型医院医疗设备管理系统设计与实现(源码+数据库+文档)
  • CSS学习(三)
  • CentOS7安装InfluxDB2简易教程
  • 数据库:信息存储与管理的关键