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

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

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”}。以下是迄今为止的我的代码:

  1. package space;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4. public class spacefinder {
  5. public static void main (String[] args) {
  6. String[] arr = {"every", "near ing", "checking", "food", "stand", "value"};
  7. Pattern pattern = Pattern.compile("\\s");
  8. for (int i = 0; i < arr.length; i++) {
  9. Matcher matcher = pattern.matcher(arr[i]);
  10. arr[i] = matcher.replaceAll("");
  11. }
  12. }
  13. }

这段代码会产生一个错误,而且我看到的每个教程都没有使用字符串数组,比如我这种情况下的 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:

  1. package space;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4. public class spacefinder {
  5. public static void main (String[] args) {
  6. String[] arr = {&quot;every&quot;, &quot;near ing&quot;, &quot;checking&quot;, &quot;food&quot;, &quot;stand&quot;, &quot;value&quot;};
  7. Pattern pattern = Pattern.compile(&quot;\\arr&quot;);
  8. Matcher matcher = pattern.matcher(arr);
  9. boolean found = matcher.find();
  10. }
  11. }

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

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

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

You can try something like this:

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

答案2

得分: -1

也许这会起作用

  1. public static String[] removeSpace(String[] ans) {
  2. for(String s:ans){
  3. while(s.contains(" ")){
  4. s = s.split(" ")[0] + s.split(" ")[1];
  5. }
  6. }
  7. return ans;
  8. }
英文:

maby this wil work

  1. public static String[] removeSpace(String[] ans) {
  2. for(String s:ans){
  3. while(s.contains(&quot; &quot;)){
  4. s = s.split(&quot; &quot;)[0] + s.split(&quot; &quot;)[1];
  5. }
  6. }
  7. return ans;
  8. }

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:

确定