如何用符号交换一组单词中的单词?

时间:2013-06-12 06:22:56

标签: java sdk

我必须用#。

交换包含字母'g'的每个单词

例如:

“我和朋友们坐在一起”将成为“我和我的朋友一起##”

“Together”和“sitting”将由#

交换

到目前为止我尝试过:

public static void main(String[] args)
{
  StringBuilder sb = new StringBuilder();
  java.lang.String s = "I am sitting together with my friends will become";
  java.lang.String sTemp[] = s.split(" ");
  for(int i=0;i<sTemp.length;i++)
  {
    if(sTemp[i].contains("g"))
    {
      sb.append("# ");
    } else
    { 
      sb.append(sTemp[i].toString()+" ");
    }
  } 
  System.out.println(sb.toString()); 
}

6 个答案:

答案 0 :(得分:1)

试试这个:

public static String swapWordsWithString (String inputString, String searchString, String swapString)
    //inputString == "I am sitting here together with my friends"
    //searchString == "g"
    //swapString == "#"
    String output = "";
    String[] words = inputString.split(" ");
    for(String x : words)
        if(x.contains(searchString))
            output = output + swapSring + " ";
        else
            output = output + x + " ";
    return output.trim();
}

答案 1 :(得分:0)

您可以先按空格将String分割为String[]。然后遍历此数组并将包含'g'的每个单词替换为'#'。之后cocatenate一个新的String,其中包含已替换数组的值,并且已完成。

答案 2 :(得分:0)

 public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
       String s = "I am sitting together with my friends will become";
       String sTemp[] = s.split(" ");
   for(int i=0;i<sTemp.length;i++){
     if(sTemp[i].contains("g")){
          sb.append("# ");

      }else{
         sb.append(sTemp[i].toString()+" ");
     }
  }
        System.out.println(sb.toString());
}

答案 3 :(得分:0)

建议使用 StringBuilder

String[] s = "I am sitting together with my friends".split(" ");

StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length; i++) {
    if (s[i].indexOf('g') != -1) {
        s[i] = "#";
    }
    sb.append(s[i]).append(' ');
}

System.out.println(sb.deleteCharAt(sb.length() - 1));

如果您已经在类路径 Apache Commons Lang (它变得更加容易)

for (int i = 0; i < s.length; i++) {
    if (s[i].indexOf('g') != -1) {
        s[i] = "#";
    }
}

// Using org.apache.commons.lang3.StringUtils
System.out.println(StringUtils.join (s, ' '));

答案 4 :(得分:0)

 String inputString = "I am sitting together with my friends";
 String outputString = "";

 for( String value : inputString.split(" ")) {
     if(value.contains("g")) {
         outputString += " #";
     } else {
         outputString += " "+ value;
     }
 }  
 System.out.println(outputString);

答案 5 :(得分:0)

public static void main(String[] args)
{
    String s = "I am sitting together with my friends";

    String[] temp = s.split(" ");

    for(int a=0; a<temp.length; a++)
    {
        if(temp[a].contains("g"))
        {
            s = s.replace(temp[a], "#");
        }
    }

    System.out.println(s);
}