如何从2个不同的字符串逐个连接

时间:2016-02-28 03:09:57

标签: c

我想逐个字母地连接两个不同的字符串。我怎样才能做到这一点? 例如:a = "hid", b = "jof" 连接字符串应为 "hjiodf"

到目前为止,我已经尝试过这么多:

#include <stdio.h>
#include <conio.h>

void concatenate2(char p[], char q[]) {
    int c = 0, d = 0;
    //Iterating through both strings
    while (p[c] != '\0' || q[d] != '\0' ) {
        //Increment first string and assign the value      
        c++;
        p[c] = q[d];
        //Increment second string and assign the value    
        d++;
        p[c] = q[d];
    }
}  //<<====== missing }

int main(void)
{
    char w[100], a[100];
    //input first string 
    printf("Input a string\n");
    gets(w);
    //input second string 
    printf("Input Second string\n");
    gets(a);
    //function call      
    concatenate2(w, a);
    //print result   
    printf("String obtained on concatenation is \"%s\"\n", w);
    getch();
    return 0;
}

3 个答案:

答案 0 :(得分:1)

您的concatenate2并没有真正进行连接,而是覆盖。请注意,您必须展开p才能为q中的字符留出更多空格 - 此时您还没有。

chqrlie已经提供了一个优雅的解决方案。此解决方案允许您使用concatenate2的确切原型。此解决方案的唯一限制是两个字符串必须具有相同的大小。

这里我提供了一个不同的解决方案。这个想法是使用额外的字符串进行连接。它要求您传入额外的concat字符串。此解决方案允许连接不同大小的字符串,例如:

Input 1st string: aaaaaaaa
Input 2nd string: bb
String obtained on concatenation is "ababaaaaaa"

请参阅下面的完整代码(注意我已将gets替换为fgets,这对输入字符串来说更安全。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void concatenate2( const char p[], const char q[], char concat[] ) 
{
    size_t p_idx = 0, q_idx = 0;
    size_t concat_idx = 0;

    // Iterating through both strings.
    while( p[p_idx] != '\0' || q[q_idx] != '\0' )
    {
        if( '\0' != p[p_idx] )
        {
            concat[concat_idx++] = p[p_idx++];
        }

        if( '\0' != q[q_idx] )
        {
            concat[concat_idx++] = q[q_idx++];
        }
    }

    concat[concat_idx] = '\0';
}


int main(void)
{
    char w[100] = "", a[100] = "", concat[200] = "";

    // Input first string.
    printf( "Input 1st string: " );
    if( NULL == fgets( w, sizeof( w ), stdin ) ) 
    {
        perror( "Invalid input" );
        return -1;
    }
    w[strlen( w ) - 1] = '\0';

    // Input second string.
    printf("Input 2nd string: ");
    if( NULL == fgets( a, sizeof( a ), stdin ) ) 
    {
        perror( "Invalid input" );
        return -1;
    }
    a[strlen( a ) - 1] = '\0';

    // Concat the two strings.
    concatenate2( w, a, concat );

    // Print the result.
    printf( "String obtained on concatenation is \"%s\"\n", concat );

    return 0;
}

答案 1 :(得分:1)

函数concatenate2无法正常工作,因为它会在使用字符之前覆盖目标缓冲区。

以这种方式修改:

void concatenate2(char p[], const char q[]) {
    int i, len = strlen(p);
    p[len + len] = '\0';
    for (i = len; i-- > 0;) {
        p[i + i + 1] = q[i];
        p[i + i] = p[i];
    }
}

如果字符串长度不同,则说明如何组合字符串的说明不清楚。

答案 2 :(得分:0)

由于您似乎无法使用C&#; s strcat而且我没有看到您必须使用数组,我建议您使用指针,例如:

    import java.io.*; 
    import java.util.Scanner; 
    import java.text.NumberFormat; 
    import java.math.*; 
    import java.util.Locale; 

    class CalPayroll extends Payroll
    { 
        Screen sc=new Screen(); 

        NumberFormat dollars=NumberFormat.getCurrencyInstance(Locale.US); 

        Scanner stdin = new Scanner(System.in);

       public static void main(String... args) { 
              CalPayroll cpr=new CalPayroll(); 
              cpr.acceptPay(); 

        } 

        public int acceptInputInt()   { 
               return in.nextInt(); 
           } 

        public char acceptInputChar() { 
              return in.next().charAt(0); 
       } 
        public float AcceptInputFloat()  { 
              return in.nextFloat();   
         } 
       public double AcceptInputDouble() { 
              return in.nextDouble(); 
       } 

        public void displayinfo() 
        { 

              calc_payroll(); 
              double _gross = getGross();
              tax(_gross); 
              double _net = getNet();

              System.out.println("Gross pay is : "+dollars.format(_gross)); 
              System.out.println("Tax is       : "+taxrate+"%"); 
              System.out.println("Net pay is   : "+dollars.format(_net)); 

        } 

        public void acceptPay() 
        { 
              CalPayroll cp=new CalPayroll(); 
              Screen sc = new Screen();
              float h,r; 
              int hs; 
              char s = 'a'
              while(s!='e' && s!='E') 
              {     
                    System.out.println("Payroll Computation"); 
                    System.out.println(" "); 
                    System.out.println("Enter number of hours worked (00.0) <0 for Quick exit>: "); 
                    h=stdin.nextFloat(); 
                    cp.setHours(h); 
                    if(h>0) 
                    { 
                          System.out.println("Enter first number of hours straight (integer or 0 to disable):"); 
                          hs=stdin.nextInt(); 
                          System.out.println("Enter hourly rate of worker (00.00): "); 
                          r=stdin.nextFloat(); 
                          sc.scrollscreen('=' as char,65,2); 
                          cp.setHrsStr(hs); 
                          cp.setRate(r); 

                          sc.scrollscreen(1); 
                          cp.displayinfo(); 
                          sc.scrollscreen(1); 

                          System.out.println("e to exit, any other letter + <Enter> to continue"); 
                          s=stdin.next().charAt(0); 

                    } 
                    else 
                    { 
                          System.out.println("e to exit, any other letter + <Enter> to continue"); 
                          s=stdin.next().charAt(0); 
                    } 

              }

        } 
    } 

    class Pay 
    { 
        private float Hours, Rate; 
        private int HrsStr; 
        public int taxrate=0; 
        double gross;


        public void setHours(float a) 
        { 
              Hours=a; 
        } 
        public void setRate(float a) 
        { 
              Rate=a; 
        } 
        public void setHrsStr(int a) 
        { 
              if(a<0) 
              { 
                    HrsStr=0; 
              } 
              else 
              { 
                    HrsStr=a; 
              } 
        } 
        public float getHours() 
        { 
              return Hours; 
        } 
        public float getRate() 
        { 
              return Rate; 
        } 
        public int getHrsStr() 
        { 
              return HrsStr; 
        } 

        public double getGross(){
            return gross;
        }


        public void calc_payroll() 
        { 
              gross=getHours()*getRate(); 
        } 

        public void tax(double a) 
        { 
              if(a>=0&&a<=399.99) 
                 taxrate=7; 
              else if(a>=400.00&&a<=899.99) 
                 taxrate=11; 
              else 
                 taxrate=17; 
        } 

    } 

    class Payroll extends Pay 
    { 
        double net; 

        public void calc_payroll() 
        { 
              super.calc_payroll(); 
              super.tax(getGross()); 
              net = getGross() - (getGross() * taxrate / 100); 
        } 


        public double getNet(){
            return net;
        }
    } 

    class Screen 
    { 
        public static void scrollscreen(int a) 
         { 
               for(int i=0;i<a;i++) 
               { 
                    System.out.println(" "); 
               }   
         } 

         public static void scrollscreen(char c, int a, int b) 
         { 
               for(int i=0;i<b;i++) 
               { 
                    for(int j=0;j<a;j++) 
                    { 
                          System.out.print(c); 
                    } 
                    System.out.println(" "); 
               } 
       } 
    } 
相关问题