[英]Add spaces between the characters of a string in Java?
I just want to add a space between each character of a string.我只想在字符串的每个字符之间添加一个空格。 Can anyone help me figuring out how to do this?
谁能帮我弄清楚如何做到这一点?
Eg given "JAYARAM"
, I need "JAYARAM"
as the result.例如,给定
"JAYARAM"
,我需要"JAYARAM"
作为结果。
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 demonstration ideone.com 演示
An alternative solution using regular expressions:使用正则表达式的替代解决方案:
yourString.replaceAll(".(?=.)", "$0 ")
Basically it says "Replace all characters (except the last one) with with the character itself followed by a space" .基本上它说“用字符本身后跟一个空格替换所有字符(最后一个除外)” 。
ideone.com demonstration ideone.com 演示
Documentation of...文档...
String.replaceAll
(including the $0
syntax) String.replaceAll
(包括$0
语法)(?=.)
syntax) (?=.)
语法)StringBuilder result = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
if (i > 0) {
result.append(" ");
}
result.append(input.charAt(i));
}
System.out.println(result.toString());
Iterate over the characters of the String and while storing in a new array/string you can append one space before appending each character.迭代字符串的字符,并在存储在新数组/字符串中时,您可以在附加每个字符之前附加一个空格。
Something like this :像这样的事情:
StringBuilder result = new StringBuilder();
for(int i = 0 ; i < str.length(); i++)
{
result = result.append(str.charAt(i));
if(i == str.length()-1)
break;
result = result.append(' ');
}
return (result.toString());
将您的字符串炸成字符数组,遍历字符数组并通过在字符后面加上一个空格来创建一个新字符串。
This would work for inserting any character any particular position in your String.这适用于在您的字符串中的任何特定位置插入任何字符。
public static String insertCharacterForEveryNDistance(int distance, String original, char c){
StringBuilder sb = new StringBuilder();
char[] charArrayOfOriginal = original.toCharArray();
for(int ch = 0 ; ch < charArrayOfOriginal.length ; ch++){
if(ch % distance == 0)
sb.append(c).append(charArrayOfOriginal[ch]);
else
sb.append(charArrayOfOriginal[ch]);
}
return sb.toString();
}
Then call it like this然后这样调用
String result = InsertSpaces.insertCharacterForEveryNDistance(1, "5434567845678965", ' ');
System.out.println(result);
I am creating a java method for this purpose with dynamic character我正在为此目的创建一个具有动态字符的 java 方法
public String insertSpace(String myString,int indexno,char myChar){
myString=myString.substring(0, indexno)+ myChar+myString.substring(indexno);
System.out.println(myString);
return myString;
}
Create a StringBuilder
with the string and use one of its insert
overloaded method:使用字符串创建一个
StringBuilder
并使用其insert
重载方法之一:
StringBuilder sb = new StringBuilder("JAYARAM");
for (int i=1; i<sb.length(); i+=2)
sb.insert(i, ' ');
System.out.println(sb.toString());
The above prints:上面的打印:
J A Y A R A M
public static void main(String[] args) {
String name = "Harendra";
System.out.println(String.valueOf(name).replaceAll(".(?!$)", "$0 "));
System.out.println(String.valueOf(name).replaceAll(".", "$0 "));
}
This gives output as following use any of the above:这给出了以下使用上述任何一种的输出:
H arendra哈恩德拉
H arendra哈恩德拉
A simple way can be to split the string on each character and join the parts using space as the delimiter.一种简单的方法是将字符串拆分为每个字符并使用空格作为分隔符连接各个部分。
Demo:演示:
public class Main {
public static void main(String[] args) {
String s = "JAYARAM";
s = String.join(" ", s.split(""));
System.out.println(s);
}
}
Output:输出:
J A Y A R A M
One can use streams with java 8:可以在 java 8 中使用流:
String input = "JAYARAM";
input.toString().chars()
.mapToObj(c -> (char) c + " ")
.collect(Collectors.joining())
.trim();
// result: J A Y A R A M
This is the same problem as joining together an array with commas.这与用逗号连接数组的问题相同。 This version correctly produces spaces only between characters, and avoids an unnecessary branch within the loop:
此版本仅在字符之间正确生成空格,并避免在循环内出现不必要的分支:
String input = "Hello";
StringBuilder result = new StringBuilder();
if (input.length() > 0) {
result.append(input.charAt(0));
for (int i = 1; i < input.length(); i++) {
result.append(" ");
result.append(input.charAt(i));
}
}
+" "
after each item in the array(except the last one, maybe)+" "
(可能除了最后一项)If you use a stringbuilder, it would be efficient to initalize the length when you create the object.如果您使用 stringbuilder,则在创建对象时初始化长度会很有效。 Length is going to be 2*lengthofString-1.
长度将是 2*lengthofString-1。
Or creating a char array and converting it back to the string would yield the same result.或者创建一个字符数组并将其转换回字符串会产生相同的结果。
Aand when you write some code please be sure that you write a few test cases as well, it will make your solution complete. A并且当您编写一些代码时,请确保您也编写了一些测试用例,这将使您的解决方案完整。
我相信他正在寻找的是 mime 代码载体返回类型代码,例如 %0D%0A(用于返回或换行符)和 \ (用于间距)或 $#032
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.