在Java中将String转换为“Character”数组

时间:2012-04-04 06:46:49

标签: java arrays string character

我想将String转换为Character类的对象数组,但我无法执行转换。我知道我可以使用toCharArray()方法将String转换为原始数据类型“char”的数组,但它无法将String转换为Character类型的对象数组。 / p>

我将如何这样做?

14 个答案:

答案 0 :(得分:166)

使用此:

String str = "testString";
char[] charArray = str.toCharArray();
Character[] charObjectArray = ArrayUtils.toObject(charArray);

答案 1 :(得分:54)

一张的衬垫:

String str = "testString";

//[t, e, s, t, S, t, r, i, n, g]
Character[] charObjectArray = 
    str.chars().mapToObj(c -> (char)c).toArray(Character[]::new); 

它的作用是:

  • 获得IntStream个字符(您可能还想查看codePoints()
  • 将每个'字符'值映射到Character(您需要强制转换为实际上它是char,然后Java会将其自动封装到Character
  • 通过调用toArray()
  • 获取生成的数组

答案 2 :(得分:32)

为什么不自己写一点方法

public Character[] toCharacterArray( String s ) {

   if ( s == null ) {
     return null;
   }

   int len = s.length();
   Character[] array = new Character[len];
   for (int i = 0; i < len ; i++) {
      array[i] = new Character(s.charAt(i));
   }

   return array;
}

答案 3 :(得分:4)

我希望下面的代码能为您提供帮助。

String s="Welcome to Java Programming";
char arr[]=s.toCharArray();
for(int i=0;i<arr.length;i++){
    System.out.println("Data at ["+i+"]="+arr[i]);
}

它正常工作,输出是:

Data at [0]=W
Data at [1]=e
Data at [2]=l
Data at [3]=c
Data at [4]=o
Data at [5]=m
Data at [6]=e
Data at [7]= 
Data at [8]=t
Data at [9]=o
Data at [10]= 
Data at [11]=J
Data at [12]=a
Data at [13]=v
Data at [14]=a
Data at [15]= 
Data at [16]=P
Data at [17]=r
Data at [18]=o
Data at [19]=g
Data at [20]=r
Data at [21]=a
Data at [22]=m
Data at [23]=m
Data at [24]=i
Data at [25]=n
Data at [26]=g

答案 4 :(得分:2)

在这种情况下,您必须编写自己的方法。使用循环并使用charAt(i)获取每个字符,并使用Character[]将其设置为arrayname[i] = string.charAt[i]数组。

答案 5 :(得分:2)

String#toCharArray会返回char数组,您拥有的数组为Character。在大多数情况下,使用charCharacterautoboxing一样无关紧要。你的情况下的问题是数组没有自动装箱,我建议你使用char(char[])数组。

答案 6 :(得分:2)

此方法将String作为参数并返回Character Array

/**
 * @param sourceString
 *            :String as argument
 * @return CharcterArray
 */
public static Character[] toCharacterArray(String sourceString) {
    char[] charArrays = new char[sourceString.length()];
    charArrays = sourceString.toCharArray();
    Character[] characterArray = new Character[charArrays.length];
    for (int i = 0; i < charArrays.length; i++) {
        characterArray[i] = charArrays[i];
    }
    return characterArray;
}

答案 7 :(得分:1)

另一种方法。

String str="I am a good boy";
    char[] chars=str.toCharArray();

    Character[] characters=new Character[chars.length];
    for (int i = 0; i < chars.length; i++) {
        characters[i]=chars[i];
        System.out.println(chars[i]);
    }

答案 8 :(得分:0)

如果您正在使用JTextField,那么它可能会有所帮助..

public JTextField display;
String number=e.getActionCommand();

display.setText(display.getText()+number);

ch=number.toCharArray();
for( int i=0; i<ch.length; i++)
    System.out.println("in array a1= "+ch[i]);

答案 9 :(得分:0)

链接总是最好的:D

String str = "somethingPutHere";
Character[] c = ArrayUtils.toObject(str.toCharArray());

答案 10 :(得分:0)

如果您不想依赖第三方API,则以下是JDK7或更低版​​本的工作代码。我没有像上面的其他解决方案那样实例化临时字符对象。 foreach循环更具可读性,请看自己:)

public static Character[] convertStringToCharacterArray(String str) {
    if (str == null || str.isEmpty()) {
        return null;
    }
    char[] c = str.toCharArray();
    final int len = c.length;
    int counter = 0;
    final Character[] result = new Character[len];
    while (len > counter) {
        for (char ch : c) {
            result[counter++] = ch;
        }
    }
    return result;
}

答案 11 :(得分:0)

我在 java.io 中使用了 StringReader 类。其中一个函数UPDATE SAFETY_ADMIN.SAFETY_USERS tbl1 SET (SUPERVISOR_ID,DEPT_ID,USER_ID,EMPLOYEE_TYPE,EMPLOYEE_NAME,EMAIL,MODIFIED_BY,MODIFIED_ON) = ( SELECT SAFETY_ADMIN.FN_GETSUPERVISORID(tbl2.SUPID),CAST(tbl2.DEPTID AS NUMBER(19)),UPPER(SUBSTR(tbl2.EMAIL,1,INSTR(tbl2.EMAIL,'@')-1)),tbl2.EMPTYPE,tbl2.EMPNAME,tbl2.EMAIL,SYS_CONTEXT('USERENV', 'OS_USER'),CURRENT_TIMESTAMP FROM PS_LOAD.EMPLOYEEDATA tbl2 WHERE tbl1.EMPLOYEE_ID = CAST(tbl2.EMPID AS NUMBER(19)) AND ( tbl1.SUPERVISOR_ID <> SAFETY_ADMIN.FN_GETSUPERVISORID(tbl2.SUPID) OR tbl1.DEPT_ID <> CAST(tbl2.DEPTID AS NUMBER(19)) OR tbl1.USER_ID <> UPPER(SUBSTR(tbl2.EMAIL,1,INSTR(tbl2.EMAIL,'@')-1)) OR tbl1.EMPLOYEE_TYPE <> tbl2.EMPTYPE OR tbl1.EMPLOYEE_NAME <> tbl2.EMPNAME OR tbl1.EMAIL <> tbl2.EMAIL ) ) where exists ( SELECT 1 FROM PS_LOAD.EMPLOYEEDATA tbl3 WHERE tbl1.EMPLOYEE_ID = CAST(tbl3.EMPID AS NUMBER(19)) AND ( tbl1.SUPERVISOR_ID <> SAFETY_ADMIN.FN_GETSUPERVISORID(tbl3.SUPID) OR tbl1.DEPT_ID <> CAST(tbl3.DEPTID AS NUMBER(19)) OR tbl1.USER_ID <> UPPER(SUBSTR(tbl3.EMAIL,1,INSTR(tbl3.EMAIL,'@')-1)) OR tbl1.EMPLOYEE_TYPE <> tbl3.EMPTYPE OR tbl1.EMPLOYEE_NAME <> tbl3.EMPNAME OR tbl1.EMAIL <> tbl3.EMAIL ) 将字符串的内容读入数组。

read(char[] cbuf)

运行它会为您提供输出:

String str = "hello";
char[] array = new char[str.length()];
StringReader read = new StringReader(str);

try {
    read.read(array); //Reads string into the array. Throws IOException
} catch (IOException e) {
    e.printStackTrace();
}

for (int i = 0; i < str.length(); i++) {
        System.out.println("array["+i+"] = "+array[i]);
}

答案 12 :(得分:0)

将字符串转换为字符数组,然后将字符数组转换回字符串

   //Givent String
   String given = "asdcbsdcagfsdbgdfanfghbsfdab";

   //Converting String to Character Array(It's an inbuild method of a String)
   char[] characterArray = given.toCharArray();
   //returns = [a, s, d, c, b, s, d, c, a, g, f, s, d, b, g, d, f, a, n, f, g, h, b, s, f, d, a, b]


  //Converting back Character array to String
  int length = Arrays.toString(characterArray).replaceAll("[, ]","").length();

  //First Way to get the string back
  Arrays.toString(characterArray).replaceAll("[, ]","").substring(1,length-1)
  //returns asdcbsdcagfsdbgdfanfghbsfdab
  or 
  // Second way to get the string back
  Arrays.toString(characterArray).replaceAll("[, ]","").replace("[","").replace("]",""))
 //returns asdcbsdcagfsdbgdfanfghbsfdab

答案 13 :(得分:0)


String[] arr = { "abc", "cba", "dac", "cda" };
    Map<Character, Integer> map = new HashMap<>();
    String string = new String();
    for (String a : arr) {
        string = string.concat(a);

    }
    System.out.println(string);

    for (int i = 0; i < string.length(); i++) {
        if (map.containsKey(string.charAt(i))) {
            map.put(string.charAt(i), map.get(string.charAt(i)) + 1);

        } else {
            map.put(string.charAt(i), 1);

        }
    }
    System.out.println(map);

//输出{a=4, b=2, c=4, d=2}