写代码处理单词列表,并修剪单词中的任何空格。

huangapple go评论69阅读模式
英文:

Write the code to process the list of words and trim any spaces out of the words

问题

这段代码应该检查字符串数组中的每个字符串,看看单词之间是否有空格。以下是一个示例:{“every”,“near ing”,“checking”,“food”,“stand”,“value”}。它应该被更改为:{“every”,“nearing”,“checking”,“food”,“stand”,“value”}。以下是迄今为止的我的代码:

package space;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class spacefinder {
   public static void main (String[] args) {
      String[] arr = {"every", "near ing", "checking", "food", "stand", "value"};
      Pattern pattern = Pattern.compile("\\s");
      for (int i = 0; i < arr.length; i++) {
         Matcher matcher = pattern.matcher(arr[i]);
         arr[i] = matcher.replaceAll("");
      }
   }
}

这段代码会产生一个错误,而且我看到的每个教程都没有使用字符串数组,比如我这种情况下的 String[] Arr,他们只使用了一个常规的 String = 语句。

英文:

This code is supposed to check through an array of strings and see if there is a space between a word. Here is an example: {“every”, “near ing”, “ checking”, “food “, “stand”, “value “}. It should be changed to hold: {“every”, “nearing”, “checking”, “food”, “stand”, “value”}. Here is my code so far:

package space;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class spacefinder {
   public static void main (String[] args) {
      String[] arr = {&quot;every&quot;, &quot;near ing&quot;, &quot;checking&quot;, &quot;food&quot;, &quot;stand&quot;, &quot;value&quot;};
      Pattern pattern = Pattern.compile(&quot;\\arr&quot;);
      Matcher matcher = pattern.matcher(arr);
      boolean found = matcher.find();
   }
}	

This code results in an error, and every tutorial I see does not use a string array, such as the String[] Arr in my case, they only use a regular String = statement.

答案1

得分: 1

你可以尝试类似这样的代码:

for(int i = 0; i < arr.length; i++) {
    arr[i] = arr[i].replace(" ", "");
}
英文:

You can try something like this:

for(int i = 0; i&lt;arr.length; i++) {
    arr[i] = arr[i].replace(&quot; &quot;, &quot;&quot;);
}

答案2

得分: -1

也许这会起作用

   public static String[] removeSpace(String[] ans) {
        for(String s:ans){
            while(s.contains(" ")){
                s = s.split(" ")[0] + s.split(" ")[1];
            }
        }
        return ans;
    }
英文:

maby this wil work

   public static String[] removeSpace(String[] ans) {
        for(String s:ans){
            while(s.contains(&quot; &quot;)){
                s = s.split(&quot; &quot;)[0] + s.split(&quot; &quot;)[1];
            }
        }
        return ans;
    }

huangapple
  • 本文由 发表于 2020年10月23日 05:12:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64490612.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定