-3

有没有办法在java中不使用任何库函数(例如:split,tocharArray等)将字符串转换为char数组

4

5 回答 5

1
String str = "abcd";
char[] arr = str.toCharArray(); // What is the wrong with this way

您可以手动构造一个 char 数组。

String str = "abcd";
char[] arr = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
    arr[i] = str.charAt(i);
}
于 2013-08-09T10:24:30.750 回答
0

这可以通过使用来实现java.io.StringReader

这是一个小片段:

public static void main(String[] args)
{
    try
    {
        String s = "hello world";

        StringReader reader = new StringReader(s);

        char[] cc = new char[1];
        cc[0] = (char) reader.read();

        char[] tmpCC = null;

        int readChar = 0;
        int lenConcatenator = cc.length;
        while((readChar = reader.read())!=-1)
        {
            ++lenConcatenator;
            tmpCC = new char[cc.length];
            System.arraycopy(cc, 0, tmpCC, 0, cc.length);

            cc = new char[lenConcatenator];
            System.arraycopy(tmpCC, 0, cc, 0, tmpCC.length);

            cc[lenConcatenator - 1] = (char) readChar;
        }

        System.out.println(cc);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
于 2014-11-03T10:48:29.480 回答
0

一个小方法(),

public Character[] toCharacterArray(String s) {
   if (s == null) {
     return null;
   }
   Character[] array = new Characer[s.length()];
   for (int i = 0; i < s.length(); i++) {
      array[i] = new Character(s.charAt(i));
   }

   return array;
}
于 2013-08-09T10:25:44.663 回答
0

使用toCharArray()的是字符串库。这个库可以用它在java.lang.String类中的实际实现来替换。没有这个,如果我们能实现请建议。

import java.util.Scanner;

public class ReverseStringWOInbuilt {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        char[] ch = sc.nextLine().toCharArray();
        char temp;  
        for (int i = 0, j = ch.length-1; i < j; i++, j--) {
            temp = ch[i];
            ch[i] = ch[j];
            ch[j] = temp;
        }
        System.out.println(new String(ch));
    }
}
于 2015-11-29T13:52:27.573 回答
0
public static char[] toMyArray(String s) {
    StringReader reader = new StringReader(s);
    int k = 0;
    int i = 0;
    char[] output = new char[s.length()];
    try {
        while ((k = reader.read()) != -1) {
            output[i] = ((char) k);
            i++;
        }
    } catch (Exception e) {

    }
    return output;
}
于 2020-07-16T20:16:01.510 回答