如何随机化字符串中的字母大小写

时间:2015-12-28 07:46:42

标签: java string algorithm

我想为Web应用程序身份验证编写一些自动化测试。登录密码区分大小写,并且始终包含至少一个字母字符。

我想写一个测试,我随机改变一个或多个字母字符的大小写。

假设密码字符串为"123te123st!"

现在我想将此字符串更改为包含至少一个大写字母的字符串。我正在尝试确保登录仍然不区分大小写,并且大小写的任何变化都将无法与密码匹配。

有人知道这样做的优雅方式吗?我已经搜索过(包括Apache Commons),但找不到帮助方法。

5 个答案:

答案 0 :(得分:0)

您可以查看randomAlphaNumeric中的RandomStringUtils,虽然您似乎无法保证它具有大写字母。要解决这个问题,您可以获得第一个小写字母并使用.toUpper()方法将其设置为大写字母。

或者,您可以生成介于0和9以及65和90以及97和122之间的随机数。第一组应该为您提供随机数,然后您可以将第二个数字转换为字符以获取大写字母(s并在最后一个数字上做同样的事情以获得你的小写字母。

话虽如此,当测试时,通常会选择预先确定的数据,而不是动态生成数据,因为这样可以更容易地进行调试。拥有一个简单的密码池也可能更容易实现,并且还可以让您更好地测试边缘情况。

答案 1 :(得分:0)

class Case
{
  public static void main(String ar[])
  {
    String s = "upperCase",split[];
    split = s.split("");
    int len = s.length(),i=0;
    while(i!=len)
    {
        if(split[i].toUpperCase() == split[i])
        {   
            System.out.println("Password Contains One UpperCase Latter");
            break;
        }
        i++;
    }
  }
}

通过使用此代码,您可以轻松检查字符串是否包含大写。 如果输出打印"密码包含一个大写后期"此消息然后字符串至少包含大写。

在这种情况下,输出需要:

enter image description here

答案 2 :(得分:0)

要生成字符串的所有大写变体,扫描字符串并将每个字母的位置存储在列表中是有意义的。这将允许您在跳过非字母字符时迭代字母。

例如,对于字符串"_a_b_c_",您希望存储位置[1, 3, 5]

接下来,创建一个与字母位置列表长度相同的布尔数组。这将代表已翻转案件的信件的位置。

要生成下一个大写变体,请假设布尔数组反向表示二进制数。将1添加到该布尔值,这意味着从头开始扫描数组,将每个true翻转到false,直到达到false,然后转到true。翻转每个位时,反转字符串中相应字符的大小写。

因此,我们得到以下2 3 - 1 = "_a_b_c_"的7个变体:

binary number  reversed   capitalized variant
        001       100      _A_b_c_
        010       010      _a_B_c_
        011       110      _A_B_c_
        100       001      _a_b_C_
        101       101      _A_b_C_
        110       011      _a_B_C_
        111       111      _A_B_C_

这是一个完整的Java实现。

import java.util.*;
import java.io.*;

public class VaryCaps {

  int wordLength,
      numLetters;
  Integer letterPositions[];
  boolean inverted[];
  StringBuffer buffer;

  public VaryCaps(String word) {
    wordLength = word.length();
    List<Integer> positionList = new ArrayList<Integer>();
    for (int i = 0; i < wordLength; ++i) {
      if (Character.isLetter(word.charAt(i))) {
        positionList.add(i);
      }
    }
    numLetters = positionList.size();
    letterPositions = positionList.toArray(new Integer[numLetters]);
    inverted = new boolean[numLetters];
    buffer = new StringBuffer(word);
  }

  private void invert(int index) {
    int pos = letterPositions[index];
    char ch = buffer.charAt(pos);
    if (Character.isUpperCase(ch)) {
      ch = Character.toLowerCase(ch);
    } else {
      ch = Character.toUpperCase(ch);
    }
    buffer.setCharAt(pos, ch);
    inverted[index] = !inverted[index];
  }

  public String next() {
    int index = 0;
    while (index < numLetters && inverted[index]) {
      invert(index++);
    }
    if (index == numLetters) {
      return null;
    }
    invert(index);
    return buffer.toString();
  }

  public static void main(String[] args) {
    VaryCaps rc = new VaryCaps("_a_b_c_");
    String s;
    while ((s = rc.next()) != null) {
      System.out.println(s);
    }
  }
}

答案 3 :(得分:0)

您可以尝试这样:

public class Test{

    public static void main(String[] args){
        String s = "1a23test12hjsd2"; // Take it as a password
        char[] c= s.toCharArray(); //Convert string in chararray
        boolean flag= false;
        StringBuilder s1= new StringBuilder();
        for(int d:c){
            if(d>=97 && d<=122 && !flag){ //Converting lowercase to upper case
                d=d-32;
                flag=true;
            }
            s1.append((char)d);
        }
        System.out.println(s1);
    }
}

答案 4 :(得分:0)

您可以使用此类生成带有大写字母约束的随机密码。

import java.util.Random;

public class RandomPasswordGenerator {
    private static final String ALPHA_CAPS  = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String ALPHA   = "abcdefghijklmnopqrstuvwxyz";
    private static final String NUM     = "0123456789";
    private static final String SPL_CHARS   = "!@#$%^&*_=+-/";

    public static char[] generatePswd(int minLen, int maxLen, int noOfCAPSAlpha, 
            int noOfDigits, int noOfSplChars) {
        if(minLen > maxLen)
            throw new IllegalArgumentException("Min. Length > Max. Length!");
        if( (noOfCAPSAlpha + noOfDigits + noOfSplChars) > minLen )
            throw new IllegalArgumentException
            ("Min. Length should be atleast sum of (CAPS, DIGITS, SPL CHARS) Length!");
        Random rnd = new Random();
        int len = rnd.nextInt(maxLen - minLen + 1) + minLen;
        char[] pswd = new char[len];
        int index = 0;
        for (int i = 0; i < noOfCAPSAlpha; i++) {
            index = getNextIndex(rnd, len, pswd);
            pswd[index] = ALPHA_CAPS.charAt(rnd.nextInt(ALPHA_CAPS.length()));
        }
        for (int i = 0; i < noOfDigits; i++) {
            index = getNextIndex(rnd, len, pswd);
            pswd[index] = NUM.charAt(rnd.nextInt(NUM.length()));
        }
        for (int i = 0; i < noOfSplChars; i++) {
            index = getNextIndex(rnd, len, pswd);
            pswd[index] = SPL_CHARS.charAt(rnd.nextInt(SPL_CHARS.length()));
        }
        for(int i = 0; i < len; i++) {
            if(pswd[i] == 0) {
                pswd[i] = ALPHA.charAt(rnd.nextInt(ALPHA.length()));
            }
        }
        return pswd;
    }

    private static int getNextIndex(Random rnd, int len, char[] pswd) {
        int index = rnd.nextInt(len);
        while(pswd[index = rnd.nextInt(len)] != 0);
        return index;
    }
}