Visualizzazione dei risultati da 1 a 8 su 8
  1. #1

    concatenare stringa

    Ciao ragazzi, volevo sapere quale fosse il miglior modo in cpp per aggiungere una stringa ad un' altra.

    Insomma in VB basta fare: strNew=str1&str2

    In cpp ho dovuto fare questo codice,

    //function addstr;
    char* addstr(char* str1, char* str2){

    int lstr1=strlen(str1);
    int lstr2=strlen(str2);

    char* str3=new char[lstr1+lstr2];

    char c;

    for (int i=0;i<(lstr1+lstr2)+1;i++){

    if (i < lstr1) {
    c=str1[i];
    }
    else {
    c=str2[i-lstr1];
    }
    str3[i]=c;
    }

    return str3;

    }

    credo ci sia un metodo più veloce.

    Grazie ciao!
    jabjoint

  2. #2
    codice:
    //function addstr;
    char* addstr(char* str1, char* str2)
    {
    	char* str3=new char[strlen(str1)+strlen(str2)];
    	strcpy( str3, str1);
    	strcat( str3, str2);
    	return str3;
    }
    01010011 01100001 01101101 01110101 01100101 01101100 01100101 01011111 00110111 00110000
    All errors are undocumented features waiting to be discovered.

  3. #3
    grazie rey!
    jabjoint

  4. #4
    O in alternativa, se puoi rinunciare alle stringhe c-like, in favore della classe string.
    codice:
    	string str1 ("Hello");
    	string str2 (" world");
    	string str3 = str1 + str2;
    	cout<<str3;
    01010011 01100001 01101101 01110101 01100101 01101100 01100101 01011111 00110111 00110000
    All errors are undocumented features waiting to be discovered.

  5. #5
    Non capisco perchè ma non mi compila utilizzando l' ultimo metodo che mi hai consigliato.
    Ho incluso -> #include <string.h>

    Questi sono gli rrori del compilatore visual c++:

    error C2040: 'str1' : 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' differs in levels of indirection from 'char *'

    error C2110: cannot add two pointers
    jabjoint

  6. #6
    #include <string>, non <string.h>.
    Amaro C++, il gusto pieno dell'undefined behavior.

  7. #7
    perfect ora funziona, ma vedo che str1, str2, str3 sono variabili gestite dalla classe o sbaglio?
    Non posso dichiararle!
    jabjoint

  8. #8
    Sono istanze della classe std::string, non capisco cosa tu indenda dire...
    Amaro C++, il gusto pieno dell'undefined behavior.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.