try to use indexOf and lastIndexOfindexOf public int indexOf(String str, int fromIndex) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. The integer returned is the smallest value k for which: k >= Math.min(fromIndex, str.length()) && this.startsWith(str, k)
If no such value of k exists, then -1 is returned. Parameters: str - the substring for which to search. fromIndex - the index from which to start the search. Returns: the index within this string of the first occurrence of the specified substring, starting at the specified index. Throws: NullPointerException - if str is null. lastIndexOf public int lastIndexOf(String str) Returns the index within this string of the rightmost occurrence of the specified substring. The rightmost empty string "" is considered to occur at the index value this.length(). The returned index is the largest value k such that this.startsWith(str, k)
is true. Parameters: str - the substring to search for. Returns: if the string argument occurs one or more times as a substring within this object, then the index of the first character of the last such substring is returned. If it does not occur as a substring, -1 is returned. Throws: NullPointerException - if str is null.然后两个相减一下应该就是了前提是\n是连续的。
//same as 50个" "
好像没有简单的方法
是不是不管含有几个\n\n\n\n\n\n\n\n\n\n\n\n\n\n\\n\n\n\n\n\n
最后都得到\n\n?
谢谢
s.replaceAll("\n\n\n","\n\n");//三个换成两个
System.out.println(s);//输出四个\n
写段代码一试就知道了.
int oldstr = " ";//11个" ";
int newstr = " ";//10个" ";
while(s1.indexOf(" ")!=-1){
s1 = s1.replaceAll(oldStr,newStr);
}
// '/n'同上
public int indexOf(String str,
int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. The integer returned is the smallest value k for which:
k >= Math.min(fromIndex, str.length()) && this.startsWith(str, k)
If no such value of k exists, then -1 is returned. Parameters:
str - the substring for which to search.
fromIndex - the index from which to start the search.
Returns:
the index within this string of the first occurrence of the specified substring, starting at the specified index.
Throws:
NullPointerException - if str is null.
lastIndexOf
public int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring. The rightmost empty string "" is considered to occur at the index value this.length(). The returned index is the largest value k such that
this.startsWith(str, k)
is true. Parameters:
str - the substring to search for.
Returns:
if the string argument occurs one or more times as a substring within this object, then the index of the first character of the last such substring is returned. If it does not occur as a substring, -1 is returned.
Throws:
NullPointerException - if str is null.然后两个相减一下应该就是了前提是\n是连续的。
还不懂吗/?
在写一次吧。
while(str.indexOf("\n\n\n") >= 0 ) //如果有多个一直循环直到没有("\n\n\n")
{
str.replaceAll("\n\n\n", "\n\n");
}