从随机位置复制在阵列内到另一个阵列

问题描述:

我有一个包含一些值的char数组。我想将该数组中的值从某个随机索引复制到某个其他随机索引。我怎样才能做到这一点 ?从随机位置复制在阵列内到另一个阵列

  #include<iostream.h> 
     using namespace std; 

     int main() 
     { 
      char ar[100]; 
      strcpy(ar,"string is strange"); 
      cout << ar ; 
      return 0; 
     } 

现在ar数组包含“string is strange”。假设我想创建另一个char数组cp,其中我想从ar的随机索引位置(例如从7到10)复制该值。有一些我们可以使用的字符串函数吗? 我知道我们可以使用strncpy函数,但它从开始索引复制到提及的字符数。是否有一些其他功能或strncpy 这将使我能够执行相同的重载版本?

+1

家庭作业?如果需要,请添加标签。 – 2012-02-09 12:52:52

+0

可能的重复http://*.com/q/2114377/198011 – 2012-02-09 12:57:38

+3

你可以想要升级到使用''的编译器。 '.h'变体是14岁。 – MSalters 2012-02-09 12:59:45

做这样

strncpy (dest, ar + 7, 2); 

一般

strncpy (destination, source + start_index, number_of_chars); 
The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there 
    is no null byte among the first n bytes of src, the string placed in dest will not be null-termi‐ 
    nated. 

因此,你需要为null手动终止字符串:

dest[nos_of_chars] = '\0'; 

UPDATE

您可以使用这样的事情:

char *make_substring (char *src, int start, int end) 
{ 
    int nos_of_chars = end - start + 1; 
    char *dest; 
    if (nos_of_chars < 0) 
    { 
    return NULL; 
    } 
    dest = malloc (sizeof (char) * (nos_of_chars + 1)); 
    dest[nos_of_chars] = '\0'; 
    strncpy (dest, src + start, nos_of_chars); 
    return dest; 
} 

当您使用C++,不要使用字符字符串处理,而不是使用String类。

+1

从7-10开始没有占用7位的10个字符,所以它是7-17。 – 2012-02-09 12:57:39

+0

错误已修复。 – phoxis 2012-02-09 13:06:16

为了复制n字符从p位置从string1开始string2,你可以使用:

strncpy(string2, string1 + p, n); 

如果你处理的C++字符串(std::string),那么你可以使用substr成员函数。

std::string string1 = "......"; 
std::string string2 = string1.substr(p, n); 

您可以通过使用例如数组中的特定位置来获取地址。 &ar[i]

例如,如果您之前return

cout << &ar[6] << '\n'; 

添加以下行,将打印

 
is strange 

你的代码是在C++中,所以使用STL - 不创建一个固定的大小字符数组,使用std :: string。这有一个方法substr(pos,n)。

因此您的代码将是:

std::string str; 
str = "string is not so strange"; 
cout << str << endl; 
std::string small; 
small = str.substr(7, 3); 
cout << small << endl; 

比使用C API做潜在的不安全指针运算容易得多。

可以使用存储器复制功能

void * memcpy (void * destination, const void * source, size_t num); 

在你的榜样

memcpy(cp,ar+p,sizeof(char)*n) 

C++

你到底想达到什么目的? '字符串是奇怪的' 让我想起了拼写检查的 - >排列

#include <algorithm> 
#include <string> 
#include <iostream> 

int main() 
{ 
    std::string s = "string is strange"; 
    std::sort(s.begin(), s.end()); 

    while (std::next_permutation(s.begin(), s.end())) 
     std::cout << s << "\n"; 

    return 0; 
} 

要真的只是交换的随机位置:http://ideone.com/IzDAj

#include <random> 
#include <string> 
#include <iostream> 

int main() 
{ 
    using namespace std; 
    mt19937 random; 

    string s = "string is strange"; 
    uniform_int_distribution<size_t> gen(0,s.size()-1); 

    for (int i=0; i<20; i++) 
    { 
     swap(s[gen(random)], s[gen(random)]); 
     cout << s << "\n"; 
    } 

    return 0; 
}