[英]How do i add a “\n” every 6 spaces in a string?
我在多維數組中有很長的字符串。 我一直試圖找出一種方法,用"\\n"
替換每個字符串中的每個第6個空格,這將導致它基本上按回車鍵。
例:
orginalString =“我要在此的第六個空格之后放置回車”;
FormatedString =“我要在\\ n的第六個空格之后輸入enter”
這就是我到目前為止所得到的。 可能完全錯誤。
public static void FormatArray(String c) {
int counter = 0;
for (int i = 0; i < c.length(); i++) {
if (c.charAt(i) == ' ') {
counter++;
}
if (counter == 6) {
counter = 0;
for (int j = 0; j < Variables.getCards().length; j++) {
StringBuilder string = new StringBuilder(
Variables.getCards()[j][1]);
string.setCharAt(i, '\n');
System.out.println(string);
}
}
}
}
這是一種解決方案:
str = str.replaceAll("(\\S+\\s+){6}", "$0\n");
替換項$0
是整個匹配項,因此會返回匹配項和換行符。
如果正則表達式不符合您的喜好,請更改它。 例如,如果要用換行符替換第6個空格,請從捕獲中排除尾隨空格:
str = str.replaceAll("((\\S+\\s+){5}\\S+)\\s+", "$1\n");
我會這樣做
// given a String str, replace every sixth space with " \n "
public static String formatString(String str) {
if (str == null) { // Handle null.
return null;
}
StringBuilder sb = new StringBuilder(); // An output buffer.
int count = 0;
for (char ch : str.toCharArray()) { // loop over the characters.
if (ch == ' ') { // test for space.
count++;
}
if (count == 6) { // every sixth space.
count = 0;
sb.append(" \n");
}
sb.append(ch);
}
return sb.toString(); // return the string.
}
// Test it.
public static void main(String[] args) {
String originalString = "i want to put enter after the sixth space of this";
String formattedString = "i want to put enter after \n the sixth space of this";
if (formatString(originalString).equals(
formattedString)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
當我運行上面的代碼時,我得到的輸出-
Yes
你說得很對。 我建議以下內容:
public static String formatStr(String a){
if(a==null) return null;
String newStr="";
int len=a.length();
int counter=0;
for(int i=0;i<len;i++){
newStr+=a.charAt(i);
if (a.charAt(i) == ' ')counter++;
if (counter == 6){
counter=0;
newStr+="\n";
//System.out.println(string);
}
}
return newStr;
}
然后,您可以調用formatStr(whatever),您將獲得返回的字符串。
您可以使用以下正則表達式:
String pattern = "(\\S*\\s){6}";
String testString = "This is just a regular test. This is just a regular test. This is just a regular test.";
Pattern p = Pattern.compile(pattern);
Matcher matcher = p.matcher(testString);
StringBuilder strBuilder = new StringBuilder();
while (matcher.find()) {
strBuilder.append(matcher.group());
strBuilder.replace(strBuilder.length() - 1, strBuilder.length(), "\n"); // To make it platform independent, user System.lineSeparator() instead of "\n" - only works in Java 7
}
if (matcher.hitEnd()) {
strBuilder.append(testString.substring(strBuilder.length()));
}
String newString = strBuilder.toString();
System.out.println(newString);
輸出將是:
This is just a regular test.
This is just a regular test.
This is just a regular test.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.