一个字符串组合问题,甚是郁闷,希望大家给一解法,不胜感谢
比如:script(大小写组合)
可以有:
script
sCript
scRipt
scrIpt
scriPt
scripT
Script
SCript
...
组合方法
问题是 我怎么把他们的所有组合存储到一个数组中呢?
[解决办法]
不需要组合,
只要存储一份 script,
然后根据这个 script,
排列组合得到具有不同大小写的 结果 即可 ~
[解决办法]
不用吧所有的存储吧.
你可以这样来实现,用6个二进制位来分别保存script这6在字母的状态,0表示小写,1表示大写。那么0x000000就表示script,0x100001就表示ScripT。
所以你可以用十进制的0到63来表示所有的状态。
你要枚举所以的状态你可以这么来写
for(int i=0;i <64;i++)
{
for(int j=0;j <6;j++)
if(i&(1 < <j))
从右向左数第j个字母大写;
else
从右向左数第j个字母小写;
}
[解决办法]
#include <cstring>
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
char str[]= "script ", tmp[8]={0};
int i, j;
for(i=0; i <=0x3f; i++)
{
int t=i;
strcpy(tmp, str);
for(j=0; j <6; j++)
{
if(t&0x01 == 1)tmp[5-j] -= 32;
t > > = 1;
}
cout < <tmp < < "\t ";
}
cout < <endl;;
system( "pause ");
return 0;
}
[解决办法]
for(i=0; i <=0x3f; i++)
{
int t=i;
strcpy(tmp, str);
for(j=0; j <6; j++)
{
if(t&0x01 == 1)tmp[5-j] -= 32;
t > > = 1;
}
cout < <tmp < < "\t ";
}
这里封装个函数,
然后你就只需要保存 script 这样一份全部小写化的就可以了 ~
[解决办法]
给你一个简单c的递归实现,满足你的要求
#include <stdio.h>
#include <string.h>
#define NUM 7 //定义字符串长度,注意 '\0 '占一个
void Combination(char ps[][NUM], char str[NUM], int n)
{
static int count = 0;
if(n == 0)
{
strcpy(ps[count], str);
count++;
return;
}
Combination(ps, str, n-1);
str[NUM-n-1] -= 0x0020;
Combination(ps, str, n-1);
str[NUM-n-1] += 0x0020;
}
void main(void)
{
char data[64][NUM]; //定义存储长度,这里你也可以通过计算长度用动态数组实现
char c[NUM] = "script ";
Combination(data, c, NUM-1);
for(int i = 0; i < 64; ++i)
printf( "%s\n ", data[i]); //输出数组中的值
}