[英]Removing every 5th char in a string and return new String
I'm trying to eliminate every 5th character of a string, unless the character is a space or a dot, and return the new string.我试图消除字符串的每 5 个字符,除非该字符是空格或点,并返回新字符串。
At the minute I can only seem to return the characters at every fifth occurrence but not manipulate them and return the new string.目前,我似乎只能在每五次出现时返回字符,但不能操作它们并返回新字符串。
Example Original String: "James scored 1 goal. His team won."示例原始字符串:“詹姆斯进了 1 个球。他的球队赢了。”
New String: "Jame scoed 1 goal! His team won!"新字符串:“詹姆斯打进 1 球!他的球队赢了!”
I've tried to use a for loop with a selection statement but can't seem to manipulate correctly and then return the full new string.我尝试将 for 循环与选择语句一起使用,但似乎无法正确操作,然后返回完整的新字符串。
public class TextProcessorTest{
public static void main(String args[]) {
String sentence = "James scored 1 goal. His team won.";
String newSentence;
StringBuffer buff = new StringBuffer();
int len = sentence.length();
for(int i=4;i<len;i=i+5){
char c = sentence.charAt(i);
System.out.print(c);
if(c == ' '){
buff.append(c);
}else if(c == '.'){
buff.append(c);
}else{
buff.append("");
}
}
newSentence = buff.toString();
System.out.println(newSentence);
}
}
Expected result is: "Jame scoed 1 goal! His team won!"预期结果是:“詹姆斯打进 1 球!他的球队赢了!”
Actual result is: "sr . . "实际结果是:“先生……”
This is pretty simple.这很简单。 Just ignore every 5th character and build new string using
StringBuilder
:只需忽略每 5 个字符并使用
StringBuilder
构建新字符串:
public static String remove(String str) {
StringBuilder buf = new StringBuilder(str.length());
for (int i = 1; i <= str.length(); i++)
if (str.charAt(i - 1) == ' ' || str.charAt(i - 1) == '.' || i % 5 != 0)
buf.append(str.charAt(i - 1));
return buf.toString();
}
StringBuffer
use in concurrent modification. StringBuffer
在并发修改中的使用。 This is thread-safe .StringBuilder
use in all not concurrent modifications. StringBuilder
在所有非并发修改中使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.