0

さて、弦を交換するには助けが必要です。

これが私がやろうとしていることの全体的なコードですが、文字列を移動することはできません。私はそれを文字に変換しようと始めましたが、返信の大部分は std::swap 関数を使用するだけであると言われましたが、これを使用することに本当に迷っています...

私の全体的な目標は、文字列の特定のセクションに指定できる文字列を並べ替えることです。これを達成するために C++ メソッド/関数を使用する方法がわかりません。

(main.cc と Permutation h もありますが、基本的には変数、骨格コードを定義するためだけです)

すべての助けに感謝します。約 2 時間後にここに戻ってきます。

更新されたコード)

    #include <iostream>   // for cout
#include <cstdio>     // for printf()
#include <sstream>    // for stringstream
#include <stdio.h>
#include <string.h>
#include "Permutation.h"
using namespace std;

Permutation::Permutation() {
    /* nothing needed in the constructor */
}

void Permutation::permute(const string& str) {

    string stringnew = str;
    int j;
    int low = 0;
    int high = str.length();

    cout << stringnew << endl;

    for (j = 0; j <= high; j++) {
        string strtemp = stringnew[j];
        std::swap((strtemp + low), (strtemp + j));
        permute(str, low + 1, high);
        std::swap(str[j + low], str[j + j]);

    }
}

void Permutation::permute(const string& str, int low, int high) {
//  int j;
//  if (low == high) {
//      cout << str << endl;
//  } else {
//      for (j = low; j <= high; j++) {
//          std::swap(str[j + low], str[j + j]);
//          permute(str, low + 1, high);
//          std::swap(str[j + low], str[j + j]);
//      }
//  }
}
4

3 に答える 3

1

クラス インターフェイスを介して作業する必要があります。から書き込み可能な文字配列を取得することはできませんstd::string

できることは、配列添え字演算子を使用して、としてアクセスすることstr[i]です。イテレータも使用できます。

これは、C++03 より前では、std::stringが文字配列である必要がなかったためです。不連続になる可能性があります。少なくとも 1 つの実装では、std::deque「配列へのポインターの配列」スタイルのバッキング ストアが使用されていました。

また、オブジェクト指向プログラミング設計の観点からは、オブジェクトの内部に手を伸ばして再配置するのは良くありません。

私は仕事から休憩したかったので、楽しみのために、配列の添字を使用して文字列をいじるいくつかのコード:

#include <cctype>
#include <string>
#include <iostream>

void uc(std::string &s) 
{
    size_t i;
    const size_t len = s.length();
    for(i=0; i<len; ++i) {
        s[i] = toupper(s[i]);
    }   
}

void mix(std::string &s) 
{
    size_t i;
    const size_t len = s.length();
    for(i=1; i<len/2+1; ++i) {
        std::swap(s[i-1], s[len-i]);
    }   
}

int main()
{
    std::string s("Test String");
    uc(s);
    std::cout << s << std::endl;
    mix(s);
    std::cout << s << std::endl;
    return 0;
}
于 2012-12-12T00:33:32.497 に答える
0

c_str() 関数を使用するだけです

std::string str("I'm a text");
char *pStr = str.c_str();
于 2012-12-11T23:44:20.843 に答える
0

これは、あなたが指摘したスレッドのように Java ではなく C++ です。初めに

char[] x 

コンパイル時に既知のサイズのテーブルに対してのみ有効な宣言です。

もう 1 つのことは、std::string には .toCharArray メソッドがありませんが、std::string からconst char*を取得するために使用できる.c_str()メソッドがあることです。

HTH

于 2012-12-11T23:46:07.100 に答える