Java “如何写入此字符串i/p”;“我爱编码”;至>&燃气轮机;o/p";I1爱4编码6“;不使用tocharray方法?
基本上,每个单词后面都会附上下面单词的字符数之和 *不使用ToCharray。Java “如何写入此字符串i/p”;“我爱编码”;至>&燃气轮机;o/p";I1爱4编码6“;不使用tocharray方法?,java,string,Java,String,基本上,每个单词后面都会附上下面单词的字符数之和 *不使用ToCharray。 分开绳子 将每个字符串的长度附加到每个拆分的字符串 连接字符串 一个简单的例子: public static void main(String[] args) { String test = "I love coding"; String[] words = test.split(" "); for (int i = 0; i < words.length; i++) {
- 分开绳子
- 将每个字符串的长度附加到每个拆分的字符串
- 连接字符串
public static void main(String[] args) {
String test = "I love coding";
String[] words = test.split(" ");
for (int i = 0; i < words.length; i++) {
String word = words[i];
words[i] = word + word.length();
}
StringBuilder builder = new StringBuilder();
for (String word : words) {
builder.append(word);
builder.append(" ");
}
String result = builder.toString().trim();
System.out.println(result);
}
publicstaticvoidmain(字符串[]args){
String test=“我喜欢编码”;
String[]words=test.split(“”);
for(int i=0;i
最简单的方法可能是使用正则表达式匹配和StringBuffer
构建一个新的字符串
String in = "I love coding";
StringBuffer out = new StringBuffer();
Matcher matcher = Pattern.compile("\\w+").matcher(in);
while (matcher.find()) matcher.appendReplacement(out, "$0" + matcher.group().length());
matcher.appendTail(out);
这将用填写“I1 love4 coding6”
,可通过out.toString()访问。除了简单之外,它还具有保留标点符号的额外好处,因此“I,love coding!”
中的将产生外的“I1,love 4 coding6!”
注意:如果我想得太多了,并且您的项目范围将“单词”定义为所有由空格分隔的实体,即在句子“coding…is fun”
中,“单词”是“coding…”
,“is”
,和“fun”
,那么您仍然可以使用此过程,交换“\\w+”模式中的
。使用“[^]+”
编译
<代码>“我爱编码!”
变成了“我爱编码!7”
请举例说明:)