在Java中的字符串字符之间添加空格? [英] Add spaces between the characters of a string in Java?

查看:4159
本文介绍了在Java中的字符串字符之间添加空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想在字符串的每个字符之间添加一个空格.谁能帮我弄清楚该怎么做?

I just want to add a space between each character of a string. Can anyone help me figuring out how to do this?

例如给定"JAYARAM",我需要"J A Y A R A M"作为结果.

E.g. given "JAYARAM", I need "J A Y A R A M" as the result.

推荐答案

除非您要遍历字符串并手动"执行操作,否则可以这样解决:

Unless you want to loop through the string and do it "manually" you could solve it like this:

yourString.replace("", " ").trim()

这会将所有空子字符串"替换为一个空格,然后修剪掉前导/尾随空格.

This replaces all "empty substrings" with a space, and then trims off the leading / trailing spaces.

ideone.com演示

使用正则表达式的替代解决方案:

An alternative solution using regular expressions:

yourString.replaceAll(".(?=.)", "$0 ")

基本上说将所有字符(最后一个字符除外)替换为字符本身,后跟一个空格"..

ideone.com演示

...的文档

  • String.replaceAll (including the $0 syntax)
  • The positive look ahead (i.e., the (?=.) syntax)

这篇关于在Java中的字符串字符之间添加空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆