129

我想将 a 转换为CharacterString类的对象数组,但我无法执行转换。我知道我可以使用该方法将字符串转换为原始数据类型“char”的数组,但它无助于将字符串转换为字符类型的对象数组。toCharArray()

我该怎么做呢?

4

14 回答 14

204

用这个:

String str = "testString";
char[] charArray = str.toCharArray();
Character[] charObjectArray = ArrayUtils.toObject(charArray);
于 2012-04-04T06:52:54.583 回答
88

班轮:

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(您需要强制转换为实际上说它真的是 a char,然后 Java 会自动将其装箱为Character
  • 通过调用获取结果数组toArray()
于 2014-12-29T14:47:33.610 回答
34

为什么不自己写一个小方法

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++) {
      /* 
      Character(char) is deprecated since Java SE 9 & JDK 9
      Link: https://docs.oracle.com/javase/9/docs/api/java/lang/Character.html
      array[i] = new Character(s.charAt(i));
      */
      array[i] = s.charAt(i);
   }

   return array;
}
于 2012-04-04T06:51:27.290 回答
5

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

   //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]

//一种方法:将字符数组转换回字符串

  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

//第二种方式:将字符数组转换回字符串

String.valueOf(characterArray);

//第三种方式:将字符数组转换回字符串

Arrays.stream(characterArray)
           .mapToObj(i -> (char)i)
           .collect(Collectors.joining());

将字符串转换为字符数组

Character[] charObjectArray =
                           givenString.chars().
                               mapToObj(c -> (char)c).
                               toArray(Character[]::new);

将字符数组转换为字符数组

 String givenString = "MyNameIsArpan";
char[] givenchararray = givenString.toCharArray();


     String.valueOf(givenchararray).chars().mapToObj(c -> 
                         (char)c).toArray(Character[]::new);

将字符数组转换为字符数组的好处您可以使用 Arrays.stream 函数来获取子数组

String subStringFromCharacterArray = 

              Arrays.stream(charObjectArray,2,6).
                          map(String::valueOf).
                          collect(Collectors.joining());
于 2019-07-29T03:37:08.853 回答
3

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

于 2012-04-04T06:51:20.037 回答
3

String#toCharArray返回一个数组char,你拥有的是一个数组Characterchar在大多数情况下,您是否使用或Character使用autoboxing并不重要。您的问题是数组没有自动装箱,我建议您使用 char ( char[]) 数组。

于 2012-04-04T06:55:23.167 回答
3

我希望下面的代码对您有所帮助。

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
于 2012-04-04T07:18:44.173 回答
2

此方法以字符串为参数并返回字符数组

/**
 * @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;
}
于 2014-05-08T04:49:33.653 回答
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]);
    }
于 2012-04-04T06:56:51.377 回答
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]);
于 2013-10-28T01:34:51.597 回答
0

链接总是最好的:D

String str = "somethingPutHere";
Character[] c = ArrayUtils.toObject(str.toCharArray());
于 2013-12-18T21:18:25.540 回答
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;
}
于 2016-06-27T08:24:08.963 回答
0

我在java.io中使用了StringReader类。其中一个函数将字符串的内容读入数组。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]);
}

运行它会给你输出:

array[0] = h
array[1] = e
array[2] = l
array[3] = l
array[4] = o
于 2016-08-29T15:43:02.603 回答
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}

于 2021-05-26T11:06:42.280 回答