在c / c ++中切换字符串中的每对单词(“ab cd ef gh ijk”变为“cd ab gh ef ijk”)

时间:2011-03-03 21:29:23

标签: c++ algorithm

在没有任何库函数的情况下,在c ++中切换字符串中的每对单词(“ab cd ef gh ijk”变为“cd ab gh ef ijk”)。

int main(){
char s[]="h1 h2 h3 h4";//sample input
switch_pair(s);
std::cout<<s;
    return 0;
}

char * switch_pair(char *s){
char * pos = s;
char * ptr = s;
int sp = 0;//counts number of space
while(*pos){
    if(*pos==' ' && ++sp==2){ //if we hit a space and it is second space then we've a pair
        revStr_iter(ptr,pos-1);//reverse the pair so 'h1 h2' -> '2h 1h'
        sp=0;//set no. of space to zero to hunt new pairs
        ptr=pos+1;//reset ptr to nxt word after the pair i.e. h3'
    }
    pos++;
}
if(sp==1) //tackle the case where input is 'h1 h2' as only 1 space is there
    revStr_iter(ptr,pos-1);
revWord(s); //this will reverse each individual word....i hoped so :'(
return s;
 }

 char* revStr_iter(char* l,char * r){//trivial reverse string algo
char * p = l;
while(l<r){
    char c = *l;
    *l = *r;
    *r = c;
    l++;
    r--;
} 
return p;
 }


char* revWord(char* s){//this is the villain....need to fix it...Grrrr
char* pos = s;
char* w1 = s;
while(*pos){
    if(*pos==' '){//reverses each word before space
        revStr_iter(w1,pos-1);
        w1=pos+1;
    }
pos++;
}
return s;
}

输入 - h1 h2 h3 h4
预期 - h2 h1 h4 h3
实际 - h2 h1 h3 4h

任何高贵的极客都可以帮助PLZ:((

2 个答案:

答案 0 :(得分:2)

IMO,到目前为止你所做的工作看起来/看起来更像C代码而不是C ++代码。我想我会从以下内容开始:

  1. 将输入分解为单词对象
  2. 交换单词对象对
  3. 重新构建重新排列的字符串
  4. 为此,我可能会定义一个非常小的字符串类。几乎所有它需要(现在)是能够创建一个字符串给定一个指向char和一个长度(或该顺序的东西)的指针,以及分配(或交换)字符串的能力。

    我还要定义一个标记器。我不确定它是真的应该是一个函数还是一个类,但就目前而言,让我们说“功能”。它所做的只是查看一个字符串,找到一个单词的开头和结尾,产生类似指向开头的指针和单词的长度。

    最后,您需要/想要一个数组来保存单词。对于第一步,您可以使用普通数组,然后在/如果您希望根据需要自动扩展数组,您可以编写一个小类来处理它。

答案 1 :(得分:1)

int Groups = 1; // Count 1 for the first group of letters
for ( int Loop1 = 0; Loop1 < strlen(String); Loop1++)
  if (String[Loop1] == ' ') // Any extra groups are delimited by space
    Groups += 1;

int* GroupPositions = new int[Groups]; // Stores the positions
for ( int Loop2 = 0, Position = 0; Loop2 < strlen(String); Loop2++)
{
  if (String[Loop2] != ' ' && (String[Loop2-1] == ' ' || Loop2-1 < 0))
  {
    GroupPositions[Position] = Loop2; // Store position of the first letter
    Position += 1; // Increment the next position of interest
  }
}

如果您不能使用strlen,请编写一个对任何字母进行计数的函数,直到它遇到空终止符'\ 0'。

相关问题