-1

我必须用 # 交换每个包含字母 'g' 的单词。

例如 :

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

“在一起”和“坐着”将被#交换

到目前为止我已经尝试过:

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()); 
}
4

6 回答 6

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();
}
于 2013-06-12T06:30:38.687 回答
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());
}
于 2013-06-12T06:38:58.607 回答
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);
}
于 2013-06-12T08:27:30.157 回答
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, ' '));
于 2013-06-12T06:44:07.317 回答
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);
于 2013-06-12T06:49:41.063 回答
0

您可以先将您的空格分割String成一个String[]。然后遍历这个数组并将每个包含“g”的单词替换为“#”。之后,使用替换数组的值cocatenate创建一个新的,你就完成了。String

于 2013-06-12T06:31:31.263 回答