在没有内置库的情况下在java中将String转换为char的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18144504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:43:35  来源:igfitidea点击:

Ways to convert String to char in java without built-in libs

javastringchar

提问by novice

is there a way to covert a string to an array of char without using any library functions (ex:- split,tocharArray etc)in java

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

回答by Ruchira Gayan Ranaweera

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

you can manually construct a char array.

您可以手动构建一个字符数组。

  String str="abcd";
   char[] arr=new char[str.length()];
   for (int i=0;i<str.length();i++){
       arr[i]=str.charAt(i);
   }

回答by Optimus Prime

A little method(),

一个小方法(),

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;
}

回答by arunrathnakumar

This can be achieved by using java.io.StringReader

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

Here is a small snippet:

这是一个小片段:

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();
    }
}

回答by Srikanth Nakka

Used "toCharArray()" which is String library. This library can be replaced by its actual implementation in java.lang.String class. Without this, if we can achieve please suggest.

使用字符串库“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));
    }
}