1

文字列の部分文字列を返す関数を書きたいと思います。

f(what string, from which index, how many chars)

文字列クラスを使用して実行しましたが、char* を使用したいのですが、方法がわかりません。string* ではなく char* を使用するようにコードを修正していただけますか? C ++では紛らわしいです。

    #include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
//index - starting at, n- how many chars
string* subString(string s, int index, int n){
    string* newString = new string("");
    for(int i = index; i < s.length() && i < n + index; i++)
        *newString += s.at(i);
    return newString;
}


int main()
{   string s1 = "Alice has a cat";
    string* output = subString(s1, 2, 4);
    cout<<(*output)<<endl;
    system("pause");
    return 0;
}
4

4 に答える 4

1
#include <iostream>
#include <stdio.h>

using namespace std;

//index - starting at, n- how many chars
char* subString(char *s, int index, int n){
    char *res = new char[n + 1];
    sprintf(res, "%.*s", n, s + index);
    return res;
}


int main()
{   
    char* s1 = "Alice has a cat";
    char* output = subString(s1, 2, 4);
    cout << output << endl;
    system("pause");
    delete[] output;
    return 0;
}
于 2012-08-30T12:08:14.813 に答える
1
#include <string.h>
char *subString(const char *s, int index, int n) {
    char *res = (char*)malloc(n + 1);
    if (res) {
        strncpy(res, s + index, n + 1);
    }
    return res;
}
于 2012-08-30T12:05:10.397 に答える
1

stringnotを使用するように修正できますstring*

string output(s1, 2, 4);

または、仕様に合わせた関数が必要な場合:

string subString(string s, int index, int n) {
    return s.substr(index, n);
}

文字列を保持するためにバッファを手動で割り当てて解放する必要があるため、使用char*するのはもっと面倒です。そうしないことをお勧めします。

于 2012-08-30T12:02:28.947 に答える
0

これがあなたのやり方だと思います。(テストしていません)。これは失敗すると null を返しますが、代わりに例外を使用するように簡単に変更できます。

char* subString(string s, int index, int n){
    if (s.length() < (n+index)) {return null;}
    char* newString = new (nothrow) char[n+1];
    if (newString){
        for(int i = 0; i < n; i++)
            {newString[i] = s.at(i + index);}
        newString[n] = '\0';
    }        
    return newString;
}
于 2012-08-30T11:56:10.780 に答える