/ *这里代码运行不正常,不计算字符串中的空格数,并用第一个字符串中的出现次数替换这些空格* /
String ip=sc.nextLine();
int count=0;
System.out.println("string");
String[] str=ip.split(" ");
for(int i=0;i<ip.length();i++){
boolean flag=true;
for(int k=0;k<i;k++){
if(ip.charAt(i)==ip.charAt(k))
flag=false;
if(flag){
for(int j=0;j<ip.length();j++){
if(ip.charAt(i)==ip.charAt(j)){
count=count+1;
}
if(count>2){
System.out.println(ip.charAt(i)+""+count);
count=0;
}
else{
System.out.println(ip.charAt(i));
}
}
}
}
}
答案 0 :(得分:0)
我会使用replace和replaceFirst的组合和两个相同的字符串
String withSpaces = "this is a test with spaces";
String copy = withSpaces;
copy = copy.replace(" ", "");
int num = (withSpaces.length() - copy.length());
withSpaces = withSpaces.replaceFirst(" ", "" + num);
System.out.println(withSpaces);
<强>输出强>
this5是一个带空格的测试
修改
在此之后摆脱其他空格只需更改为
withSpaces = withSpaces.replaceFirst(" ", "" + num).replace (" ", "");
答案 1 :(得分:0)
您可以使用以下代码计算a中的空格数 特殊字符串然后用count替换所有空格。
代码:
String testwithspaces = "this is the string with spaces";
System.out.println("Orignal String :"+testwithspaces);
int count = testwithspaces.length() - testwithspaces.replace(" ", "").length();
System.out.println("Number of spaces ="+count);
String replaceSpaceWithCount= testwithspaces.replace(" ",""+count);
System.out.println("String with space replaced by count : "+replaceSpaceWithCount);
输出
Orignal String :this is the string with spaces
Number of spaces =5
String with space replaced by count : this5is5the5string5with5spaces
你必须在这里使用两个替换语句:
计算空格数。
用该计数替换空格。