0

好的,所以我需要一些帮助来交换我的字符串。

这是我正在尝试做的整体代码,但我不能只是移动字符串。我开始尝试将其转换为字符,但大多数回复说只使用 std::swap 函数,但是我真的迷失在使用这个......

我的总体目标是置换一个字符串,可以将其指定到字符串的某个部分。我是 C++ 新手,我只是不确定如何使用 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不需要是字符数组。它可能是不连续的。至少有一个实现使用了一种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

这是 C++ 而不是你指出的线程中的 java。首先

char[] x 

仅适用于编译时已知大小的表的有效声明。

另一件事是 std::string 没有 .toCharArray 方法,但它有.c_str()方法,您可以使用它从 std::string获取const char* 。

高温高压

于 2012-12-11T23:46:07.100 回答