java 在java中将char数组的一部分转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16850937/
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-11-01 00:09:58  来源:igfitidea点击:

Converting a part of a char array to string in java

javastringchar

提问by user2439222

I have a character array:

我有一个字符数组:

char[] a = {'I', ' ', 'm', 'i', 's', 's', ' ', 'y', 'o', 'u', '.'};

char[] a = {'I', ' ', 'm', 'i', 's', 's', ' ', 'y', 'o', 'u', '.'};

Now I want to convert a part of that character array(for example:'m', 'i', 's', 's') to a string. How can I do that?

现在我想将该字符数组的一部分(例如:'m'、'i'、's'、's')转换为字符串。我怎样才能做到这一点?

回答by JB Nizet

You want to create a String. How about looking at the javadoc of String, find the constructors, and finding this one:

你想创建一个字符串。如何查看String 的 javadoc,找到构造函数,然后找到这个:

String(char[] value, int offset, int count)

Allocates a new String that contains characters from a subarray of the character array argument.

字符串(字符 [] 值,整数偏移量,整数计数)

分配一个新字符串,其中包含来自字符数组参数的子数组的字符。

回答by Ted Hopp

Try the String(char[], int, int)constructor:

尝试String(char[], int, int)构造函数

String s = new String(a, 2, 4);

That will construct a Stringfrom the characters of array astarting at offset 2 and a length of 4.

这将从偏移量 2 和长度为 4String的数组字符构造一个a

回答by DevZer0

If you want to convert the whole char array you should do

如果你想转换整个 char 数组,你应该这样做

String s = new String(a);

String s = new String(a);

回答by Dhananjay Joshi

First I want to know that you want which part of char array

首先我想知道你想要char数组的哪一部分

there are so many way to get part of that array

有很多方法可以获得该数组的一部分

First
String s = new String(a);

第一个
字符串 s = new String(a);

Second you can get part of array as mention below

其次,您可以获得数组的一部分,如下所述

public class Test2 {

公共类 Test2 {

public static void main(String[] args) {
    char[] a = {'I', ' ', 'm', 'i', 's', 's', ' ', 'y', 'o', 'u', '.'};
    String s = new String(a);
    System.out.println("Whole Array :- "+s);
    String[] array = s.split(" ");
    System.out.println("\n Part Of Array");
    for (String string : array) {
        System.out.println(string);
    }

}

}

}