首页 > 试题广场 >

给定字符串(ASCII码0-255)数组,请在不开辟额外空间

[问答题]
给定字符串(ASCII码0-255)数组,请在不开辟额外空间的情况下删除开始和结尾处的空格,并将中间的多个连续的空格合并成一个。例如:"   i    am a      little boy.    ",变成"i am a little boy",语言不限,但不要用伪代码作答,函数输入输出请参考如下的函数原型:
C++函数原型:
void FormatString(char str[],int len){
}

<pre class="prettyprint lang-cpp">void FormatString(char str[], int len) { if(str == NULL || len <= 0) return; int i = 0, j = 0; while(str[i] == ' ')//开头的空格 i++; while(str[i] != '\0') { if(str[i] == ' ' && (str[i+1] == ' ' || str[i+1] == '\0'))//中间或者结尾的空格 { i++; continue; } str[j++] = str[i++]; } str[j] = '\0'; }</pre> <br>
编辑于 2016-08-11 10:03:51 回复(13)
public class ClearSpace {
	public static void main(String[] args) {
		String st = " i am a   little boy.  ";
		char[] str = st.toCharArray();
        int i=0,j=0;
        while(str[i]==' '){
        	i++;      	
        }
        while(i<=str.length-1){
        	if(str[i]==' '&&(i==str.length-1||str[i+1]==' ')){ //如果中间空格的之后还存在空格的话,或者是结尾的话。
        		i++;    	
        		continue;
        	}
        	str[j++]=str[i++];
        	
        }
        for(int o=0;o<j;o++){
        	System.out.print(str[o]);
        }
	}
	
}

发表于 2016-09-03 20:47:28 回复(4)
public static String formatString(String str){//运用正则表达式 Java代码
str = str.trim();
str = str.replaceAll("\\s{1,}", " ");
return str;
}
发表于 2015-09-18 15:31:50 回复(3)
public class FormatString {
	public void FormatStringX(char str[],int len){
		int index = 0;
		int currentIndex = 0;
		// at the beginning
		index = findPosition(str,0);
		// begin at the first non-space character
		while(index <= len - 1){
			// copy
			if (str[index] != ' ') {
				str[currentIndex++] = str[index++];
			}
			else {
				index = findPosition(str, index);	
				str[currentIndex++] = ' ';
			}		
		}
		str[currentIndex] = '\0';	
	}
	public int findPosition(char str[],int index){
		while(index < str.length && str[index] == ' '){
			index++;
		}
		return index;
	}

发表于 2015-09-12 15:37:14 回复(0)
#include <iostream>
using namespace std;
void formatString(char str[],int length)
{
    bool isLastNotSpace=false;
    int newStrIndex=0;
    int i=0;
    while(str[i]!='\0')
    {
        if(str[i]!=' ')
        {
            str[newStrIndex++]=str[i++];
            isLastNotSpace=true;
        }
        //如果遍历得到的此字符是空格
        else
        {
            //前一个遍历得到不是空格,则这个字符也需要保留
            if(isLastNotSpace)
            {
                str[newStrIndex++]=str[i++];
                isLastNotSpace=false;
            }
            else
            {
                i++;
            }
        }
    }
    //通过上面的处理,最后一个字符仍然有可能是空格
    if(newStrIndex>0 && str[newStrIndex-1]==' ')
    {
        str[newStrIndex-1]='\0';
    }
    else
    {
        str[newStrIndex]='\0';
    }
}
int main()
{
    char a[]="   i    am a      little boy.    ";
    cout<<"原字符串:"<<a<<endl;
    formatString(a,sizeof(a)/sizeof(a[0]));
    cout<<"新字符串:"<<a<<endl;
    return 0;
}
编辑于 2018-06-04 20:56:23 回复(0)
 void FormatString(char str[], int len)
{
    int flag = 0;
    int i = 0;
    int j = 0;
    while(j < len)
    {
      if(str[j] == ' ')
      {
         j++;
         flag = 0;
     }
      else
     {
        if(i>0 && flag==0)
       {
         str[i] = ' ';
         i++;
        flag = 1;
       }
       str[i] = str[j];
       i++;
       j++; 
    }
  }
  str[i] = '\0';
}
发表于 2015-07-10 14:36:26 回复(0)
arron回答三风格(解释/代码/结果),

奉上解释
   复杂度 o(N)
   操作依然是基础的字符串搬运,遇到连续空格就省略当前的空格,利用现有数组空间。
   难点在于:头部和尾部的处理。

奉上可运行代码(含测试用例)
//#define  xFormatString //给定字符串(ASCII码0-255)数组, 优化
#ifdef xFormatString //no other space;
void FormatString(char str[],int len)
{
 assert(str !=NULL || len <0 || str[len-1]!='\0');
 int i=0 , j=0,  k =0;
 while( str[i] == ' ')i++; //find i;
 while( str[i] !='\0')//不要随意的使用while(str[i++])
 {
 if (str[i] == ' ' && str[i+1] == ' ' || str[i+1] == '\0')//完善不容易
 {
 i++;
 continue;
 }
 str[j++] = str[i++];
 }
 str[j]='\0';
}
int main(){
 char a[]=" i    am a      little boy.    ";
 //char a[]="           begin";
 //char a[]="end ";
 //char *pa=a;
 unsigned int len=strlen(a);
 FormatString(a,len);
 printf("%s\n",a);
 system("pause");
 return 0;
}
#endif

奉上结果(见右侧):


编辑于 2015-01-28 19:11:41 回复(1)
#include <iostream>
#include <stdlib.h>
#include <string>
#include <cstringt.h>
//#include <stdio.h>
using namespace std;

void FormatString(char str[], int len)
{
	for (int i = 0; i < len-1;i++)
	{
		if (str[i]==' '&&str[i+1]==' ')
		{
			for (int j = i ; j < len-1;j++)
			{
				str[j] = str[j + 1];
			}
			len--;
			i--;
		}
	}
	if (str[len-1]==' ')
	{
		str[len - 1] = '\0';
	}
	if (str[0]==' ')
	{

		for (int i = 0; i < len - 1; i++)
		{
			str[i] = str[i + 1];
		}
		len--;
	}
	
}



int main()
{
	//char *str=new char[1000];
	char str[1000];
	//cin >> str;
	strcpy_s(str, "   I              am       a      little            boy            .                      ");
	int len = strlen(str);
	FormatString(str, len);
	for (int i = 0; str[i] != '\0';i++)
	{
		cout << str[i] ;
	}
	//cout << endl;

	//delete[]str;
	//str = NULL;
	system("pause");
	return 0;
}

发表于 2016-03-30 20:07:28 回复(0)
def FormatString(s):
    s = bytearray(s, encoding="utf-8")
    i, j = 0, 1
    n = len(s)
    if not n:
        return
    count = 0
    while j < n:
        if s[j] == ord(" "):
            count += 1
            j += 1
        elif s[j] != ord(" ") and count <= 1:
            if s[j-1] == ord(" "):
                s[i] = ord(" ")
                i += 1
            s[i] = s[j]
            i += 1
            j += 1
        else:
            count = 0
            if i > 0:
                s[i] = ord(" ")
                i += 1
            s[i] = s[j]
            i += 1
            j += 1
    s = (s[:i]).decode("utf-8")
    return s
              
            
编辑于 2020-10-12 08:40:51 回复(0)
 
public class Solution{
    public static void main(String[]  args){
        String s=" i am a    little boy.";
        char[] str=s.toCharArray();
        StringBuilder sb=new StringBuilder();
        int i=0;
        while(str[i]==' '){
            i++;
        }
        while(i<=str.length-1){
            if(str[i]==' '&&(str[i+1]==' '||i==str.length-1)){
                    i++;
                    continue;
              }
            sb.append(str[i++]);
        }
        System.out.println(sb.toString());
    }
}
发表于 2019-04-11 21:11:01 回复(0)
 
发表于 2018-09-09 18:05:54 回复(0)
public static String formatString(String str){
    StringBuilder sb = new StringBuilder(str.trim());
    int i = 1;
    while(i < sb.length()){
        if(sb.charAt(i) == ' ' && sb.charAt(i - 1) == ' ')
           sb.deleteCharAt(i);
        else
            i++;
    }
    return sb.toString();
}

发表于 2018-09-09 15:23:39 回复(0)
public static void FormatString(char[] str,int len){                  for(int i=-1,j=0,k=0;i<len;i=j){             for(j=i+1;j<len;j++)                 if(str[j]==' ')                     break;                          for(k=j+1;k<len;k++)                 if(str[k]!=' ')                     break;                          while (j<len&&k<len&&str[k]!=' ') {                 str[j++] = str[k];                 str[k] = ' ';                 k++;             }         }                  for(int i=0;i<str.length;i++){             if(str[i]=='.')                 break;             System.out.print(str[i]);         }     }

发表于 2018-09-08 23:35:51 回复(0)
public void FormatString(char[] str,int len){
    String s=new String(str);
   s=s.trim();
    bool flag=false;
   for(int i=0;i<s.length()-1;++i){
       if(s.charat(i)!=" "){
          flag=false;
          continue;
        }
        else{
            if(flag){
                s.charat(i)=="";
            }
            flag=true;
        }
    }
    str=s.toCharArray();
    

}

发表于 2018-07-17 09:36:05 回复(0)
//没有测试用例,也不知道对不对。。。


/**
 * Created by huali on 2018/5/26.
 */
public class Main{
//    给定字符串(ASCII码0-255)数组,
// 请在不开辟额外空间的情况下删除开始和结尾处的空格,
// 并将中间的多个连续的空格合并成一个。例如:"   i    am a      little boy.    ",
// 变成"i am a little boy",语言不限,但不要用伪代码作答。
    public static void main(String[]args)
    {
        //String str = "   i    am a      little boy.    ";
        String str = "i am a boy. ";
        char [] ch = str.toCharArray();
        formatString(ch, ch.length);
        //for(int i=0;i<ch.length;i++)
        //{
        //    if(ch[i]==ch[i+1]&&ch[i]==' ')
        //        break;
        //    System.out.print(ch[i]);
        //}
        System.out.println();
    }

    private static void formatString(char[] ch, int length) {
        int count = 0;
        char be = ' ';
        for(int i=0;i<ch.length;i++)
        {
                if(ch[i]==' ')
                {
                    be = ' ';
                    continue;
                }
                else
                {
                    if(count!=0&&be ==' ')
                        System.out.print(' ');
                    char tmp = ch[i];
                    ch[i] = ch[count];
                    ch[count] = tmp;
                    System.out.print(ch[count]);
                    be = tmp;
                    count++;
                }
        }
    }
}
发表于 2018-05-26 17:18:53 回复(0)
import re
s="   i    am a      little boy.    "
s=s.strip()
s=re.sub(' +'," ",s)
print s
发表于 2018-04-09 16:16:07 回复(0)
#include <iostream>
#include <cstring>
using namespace std;
void FormatString(char str[],int len) {
    if(str==nullptr||len<=0)
         return;
    char *p1=str,*p2=str;
    bool is=false;
    while(*p1!='\0') {
         if(*p1!=' ') {
            if(is)
                *p2++=' ';
            *p2++=*p1;
         }
         else {
            if(p2!=str) 
                is=true;
         }
         ++p1;
    }
    *p2='\0';
}
int main()
{
    char str[]="   i am a     little boy.   ";
    FormatString(str,strlen(str));
    cout<<str<<endl;
    return 0;
}

发表于 2018-03-16 20:59:15 回复(0)
 
class Solution(self, ):
    return 
发表于 2018-01-16 21:56:40 回复(0)


发表于 2017-03-15 16:08:28 回复(0)
void FormatString(char str[], int len){
	int spaceIndex = 0;
	int newLen = 0;
	bool isPevSpace = false;
	bool isFirstSpace = true;
	for (int i = 0; i < len; i++)
	{
		if (str[i] == ' ')
		{
			if (isPevSpace && isFirstSpace)
			{
				spaceIndex = i;
			}
			else if (isFirstSpace)
			{
				continue;
			}
			else if (!isPevSpace)
			{
				str[spaceIndex++] = ' ';
			}
			isPevSpace = true;
		}
		else
		{
			isFirstSpace = false;
			str[spaceIndex++] = str[i];
			newLen++;
			isPevSpace = false;
		}
	}

	str[spaceIndex] = '\0';
}
发表于 2017-02-22 15:50:23 回复(0)