我想编写一个函数,它从java中的数组中删除多个连续的空格

时间:2016-02-17 22:11:46

标签: java trim

我想编写一个trim()函数,它将一个字符数组作为输入,并从数组中删除多个连续的空格。这是我的代码:

public class Trim {

    public static char [] trim(char [] input) {
    int j = 0;

        for (int i = 0; i < input.length; i++)
        {
            if (input[i] != ' ')
            {
                input[j++] = input[i];
            }

            if (i == input.length - 1)
            {
                while (j < input.length)
                {
                    input[j] ='\0';
                    j++;
                }
            }
        }

        return input;
    }

这是我的测试人员档案

public static void main(String [] args){
    char [] input = {'T','h','i','s',' ',' ',' ',' ','i','s'};

    for (int i = 0; i< input.length; i++){
      System.out.print(input[i]);
    }

    System.out.println("");
    char []  output = trim(input);

    for (int i = 0; i< output.length; i++){
        System.out.print(output[i]);
    }

    System.out.println("");    
    }
}

预期产出:

This me

我的输出显示

Thisme

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:0)

这是一个修改原始数组的工作示例。意思是将i始终放在下一个字符上,并且只要它们都是空格就停止j。换句话说,当其中任何一个是非文本空间时提前j

public static void trim(char[] input)
{
    int j = 0;
    for (int i = 1; i < input.length; i++)
    {
        if (input[j] != ' ' || input[i] != ' ')
        {
            j++;
        }
        input[j] = input[i];
    }
    input = Arrays.copyOf(input, j + 1);
}

答案 1 :(得分:0)

这是一个有效的例子:

public static char [] trim(char [] input){
  //Your code here
  char [] output =  new char[input.length];      
  int i=0;
  int count=0;
  for( int j =0; j< input.length; j++ )
  {           
     if ( input[j]!= ' ')
     {
        count=0;
        output[i] = input[j] ;
        i++;           
     }
     else {
        count++; 
     } //System.out.println( '\0');
     if( count==1)
     {
       output[i]= ' ';
       i++;
     }
  }
  return output;
 }

答案 2 :(得分:-1)

您正在跳过每个空格字符。

做这样的事情:

if ((lastchar== ' ')

{
if ((lastchar== ' ') && (nextchar==' ')
{
 ;}

// this will use the final ' ' as a char but ignore all previous!