我必须用#。
交换包含字母'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());
}
答案 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);
}