如何在同一个类中将splitbuilder与splitbuilder一起使用?

时间:2015-12-23 05:22:03

标签: java split stringbuilder

StringBuilder隐藏元音:

String bienvenue_intro = " Welcome! Java First Semester: 455, java street: City (State): Country: 575757 ";
StringBuilder sb = new StringBuilder(bienvenue_intro);
String[] introduction = bienvenue_intro.split(":"); 
for (int i = 0; i < bienvenue_intro.length(); i++) {
    char c = bienvenue_intro.charAt(i);
    if ((c == 'A') || (c == 'a') ||
        (c == 'E') || (c == 'e') ||
        (c == 'I') || (c == 'i') ||
        (c == 'O') || (c == 'o') ||
        (c == 'U') || (c == 'u')) {
            sb.setCharAt(i, '*');
    }
}
System.out.println(bienvenue_intro);
System.out.println(sb.toString());

上述代码的输出是:

Welcome! Java First Semester: 455, java street: City (State): Country: 575757 
 W*lc*m*! J*v* F*rst S*m*st*r: 455, j*v* str**t: C*ty (St*t*): C**ntry: 575757 

方法拆分以打破行:

for (int i = 0; i < introduction.length; i++)
    System.out.println(introduction[i]);

使用split + string builder所需的输出是:

W*lc*m*! J*v* F*rst S*m*st*r

 455, j*v* str**t

 C*ty (St*t*)

 C**ntry

 575757 

但两者在一起它不起作用!甚至可以使用Split方法将StringBuilder组合在一起吗?

4 个答案:

答案 0 :(得分:5)

不要先拆分String,先拆分转换。 StringBuilder将为您执行就地字符替换,并使用toString()获取替换的字符串并对其执行拆分。

String bienvenue_intro = " Welcome! Java First Semester: 455, java street: City (State): Country: 575757 ";
StringBuilder sb = new StringBuilder(bienvenue_intro);

for (int i = 0; i < bienvenue_intro.length(); i++) {
  char c = bienvenue_intro.charAt(i);
  if (   (c == 'A') || (c == 'a')
      || (c == 'E') || (c == 'e')
      || (c == 'I') || (c == 'i')
      || (c == 'O') || (c == 'o')
      || (c == 'U') || (c == 'u')) {
    sb.setCharAt(i, '*');
  }
}
System.out.println(bienvenue_intro);
//System.out.println(sb.toString());

String[] introduction = sb.toString().split(":");  //<-- Do the split here after replacements.
for (String string : introduction) {
  System.out.println(string);
}

输出:

 W*lc*m*! J*v* F*rst S*m*st*r
 455, j*v* str**t
 C*ty (St*t*)
 C**ntry
 575757 

答案 1 :(得分:3)

有一种更好,更简单的方法:)

replaceAll()split()

public static void main(String[] args) {
    String bienvenue_intro = " Welcome! Java First Semester: 455, java street: City (State): Country: 575757 ";
    String[] arr = bienvenue_intro.replaceAll("(?i)[aeiou]+", "*").split(":");

    for(String s : arr) {
        System.out.println(s);
    }
}

 W*lc*m*! J*v* F*rst S*m*st*r
 455, j*v* str*t
 C*ty (St*t*)
 C*ntry
 575757 

答案 2 :(得分:1)

我想扩展@YoungHobbit给出的答案。我不是专家,但这些是我的观察:

我的看法:

String bienvenue_intro = " Welcome! Java First Semester: 455, java street: City (State): Country: 575757 ";
String mod_str = bienvenue_intro.replaceAll( "(?i)[aeiou]", "*" );
String[] introduction = mod_str.split(":");
for (String string : introduction) {
  System.out.println(string);
}

答案 3 :(得分:0)

我相信你的方法是错的:已经有一个API可以在一个易于阅读的代码行中执行此操作:

System.out.println(bienvenue_intro.replaceAll("[aeiouAEIOU]", "*").replace(":", "\n"));