Java中的字符与字符串?

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

Char vs String in Java?

javastringchar

提问by

I am learning Java this year as part of the AP Computer Science curriculum, and while I was reading about "Char" and "String" I could not understand why one would bother to use "Char" and only be able to store one character rather than just use "String" and be able to store much more than that. In short what's the point of "char" if it can only store a single character?

作为 AP 计算机科学课程的一部分,我今年正在学习 Java,当我阅读“Char”和“String”时,我不明白为什么人们会费心使用“Char”而只能存储一个字符不仅仅是使用“字符串”并且能够存储更多。简而言之,如果“char”只能存储一个字符,它的意义何在?

回答by MobileMon

Because the char takes up less memory!

因为char占用的内存更少!

Also the char is stored in memory and NOT as a reference value so theoretically its faster to access the char (You'll understand that more later)

此外,char 存储在内存中,而不是作为参考值,因此理论上访问 char 会更快(稍后您会了解更多)

***Note: I once had this same thought when I first started programming about why use an int when you can use a long and not have to worry about large numbers. This tells me you're on your way to be a great programmer! :)

***注意:当我第一次开始编程时,我曾经有过同样的想法,为什么在可以使用 long 而不必担心大数的情况下使用 int。这告诉我你正在成为一名优秀的程序员!:)

回答by redFIVE

chartake up less memory for times when you really only need one character. There are also multiple other applications for using a single character.

char当您真的只需要一个字符时,占用的内存较少。还有多个其他应用程序可以使用单个字符。

charis a primitive datatype while stringis an object which comes at greater overhead.

char是一个原始数据类型,而string是一个开销更大的对象。

A stringis also made up of char, so there's that too.

Astring也由 组成char,所以也有。

回答by dasblinkenlight

Strings are objects. Objects always go on the dynamic storage. Storing one-character string would require at least a dozen of bytes.

Strings 是对象。对象总是在动态存储上。存储一个字符的字符串至少需要十几个字节。

chars (not Chars) are primitives. They take fixed amount of space (2 bytes). In situations when you need to process a single character, creating one-character string is a waste of resources. Moreover, when you expect to see a single character, using strings would require validation that the data passed in has exactly one character. This would be unacceptable in situations when you must be extremely fast, such as character-based input and output.

chars(不是Chars)是基元。它们占用固定的空间量(2 个字节)。在需要处理单个字符的情况下,创建单字符字符串是一种资源浪费。此外,当您希望看到单个字符时,使用字符串需要验证传入的数据是否只有一个字符。这在您必须非常快的情况下是不可接受的,例如基于字符的输入和输出。

To summarize, you need a charbecause of

总而言之,你需要一个char因为

  • Memory footprint- a charis smaller than a Stringof one character
  • Speed of processing- creating objects carries an overhead
  • Program's maintainability- Knowing the type makes it easier for you and for the readers of your code to know what kind of data is expected to be stored in a charvariable.
  • 内存占用- achar小于String一个字符的 a
  • 处理速度- 创建对象会带来开销
  • 程序的可维护性- 了解类型使您和您的代码的读者更容易知道期望将什么样的数据存储在char变量中。

回答by Brian Gordon

charis a primitive type while Stringis a true Object. In some cases where performance is a concern it's conceivable that you would only want to use primitives.

char是原始类型,String而是 true Object。在某些情况下,性能是一个问题,可以想象您只想使用原语。

Another case in which you would want to use charis when you're writing Java 1.0 and you're tasked with creating the Stringclass!

您想要使用的另一种情况char是当您正在编写 Java 1.0 并且您的任务是创建String类时!

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

回答by Cruncher

Everything in java can be reduced to primitive types. You can write any program with primitive types. So you need some kind of minimalist way of storing text. A char is also really just a byte, that is interpreted as a character.

Java 中的所有内容都可以简化为原始类型。您可以使用原始类型编写任何程序。所以你需要某种存储文本的极简方式。char 实际上也只是一个字节,它被解释为一个字符。

Also if you want to loop though all characters in a string you would do:

此外,如果您想遍历字符串中的所有字符,您可以这样做:

char[] chArr = str.toCharArray();

for(int i = 0 ; i < chArr.length ; i++)
{
    //do something with chArr[i];
}

This would be much more awkward trying to substring out an exact character from the String.

尝试从字符串中分出一个确切的字符会更尴尬。

回答by Daniel Kaplan

People are mentioning memory concerns, which are valid, but I don't think that's a very important reason 99% of the time. An important reason is that the Java compiler will tell you if you make a mistake so you don't have to figure it out on your own.

人们提到内存问题,这是有道理的,但我认为在 99% 的情况下这不是一个非常重要的原因。一个重要的原因是 Java 编译器会告诉您是否犯了错误,因此您不必自己弄清楚。

For example, if you only want 1 character for a variable, you can use a charto store the value and now nobody can put anything else in there without it being an error. If you used a Stringinstead, there could be two characters in the String even though you intended that to never be possible. In fact, there could be 0 characters in the String which would be just as bad. Also, all your code that uses the Stringwill have to say "get the first character of the String" where it could simplysay, "give me the character".

例如,如果您只想要一个变量的 1 个字符,您可以使用 achar来存储值,现在没有人可以在其中放入任何其他内容而不会出错。如果您使用 aString代替,则字符串中可能有两个字符,即使您希望这永远不可能。事实上,字符串中可能有 0 个字符,这同样糟糕。此外,所有使用 的代码String都必须说“获取字符串的第一个字符”,它可以简单地说“给我这个字符”。

An analogy (which may not make sense to you yet, unfortunately) would be, "Why would I say a Personhas a Namewhen I could say a Personhas a List of Names?" The same reasons apply. If you only want a Personto have one Name, then giving him a list of Names adds a lot maintenance overhead.

打个比方(这可能没有什么意义,你的呢,可惜)将是,“为什么我会说Person有一个Name时候,我可以说Person有一个名单Names?” 同样的理由也适用。如果你只想要 aPerson有一个Name,那么给他一个Names的列表会增加很多维护开销。

回答by RaptorDotCpp

You could consider this analogy:

你可以考虑这个比喻:

You need one apple. Would you prefer to have one apple in your hand, or a big box that could contain more apples, but only needs to contain the one?

你需要一个苹果。你更喜欢手里拿着一个苹果,还是一个可以装更多苹果但只需要装一个的大盒子?

The charprimitive datatype is easier to work with than the Stringclass in situations where you only need one character. It's also a lot less overhead, because the Stringclass has a lot of extra methods and information that it needs to store to be efficient at handling string with multiple characters. Using the Stringclass when you only need one character is basically overkill. If you want to read from a variable of both types to get the character, this is the code that would do that:

char原始数据类型是比较容易的工作具有比String在你只需要一个字符的情况下类。它的开销也少得多,因为String该类有很多额外的方法和信息,需要存储这些方法和信息才能有效地处理具有多个字符的字符串。String当您只需要一个字符时使用该类基本上是矫枉过正。如果您想从两种类型的变量中读取以获取字符,则可以使用以下代码:

// initialization of the variables
char character = 'a';
String string = "a";
// writing a method that returns the character
char getChar()
{
    return character; // simple!
}
char getCharFromString()
{
    return string.charAt(0); // complicated, could fail if there is no character
}

If this code looks complicated, you can ignore it. The conclusion is that using Stringwhen you only need one character is overcomplicating things.

如果这段代码看起来很复杂,你可以忽略它。结论是,String当您只需要一个字符时使用会使事情变得过于复杂。

Basically, the Stringclass is used when you need more than one character. You could also just create an array of chars, but then you would not have the useful methods of the Stringclass, such as the .equals()and .length()methods.

基本上,String当您需要多个字符时使用该类。您也可以只创建一个chars数组,但是这样您就不会拥有String该类的有用方法,例如.equals().length()方法。

回答by Vulcronos

Lot of answers here already. While the memory concerns are valid, you have to realize there are times when you want to directly manipulate characters. The word ladder game

这里已经有很多答案了。虽然内存问题是有效的,但您必须意识到有时您想直接操作字符。该字梯游戏

where you try to turn one word into another by changing one character at a time is an example I had to do in a programming class. Having a char type lets you manipulate a singe character at a time. It also lets you assign an int to a char that maps to your local character set.

你试图通过一次改变一个字符来把一个词变成另一个词是我在编程课上做的一个例子。拥有 char 类型可让您一次操作单个字符。它还允许您将 int 分配给映射到本地字符集的 char。

You can do thing like char c = 97; and that will print out as a. You can do things like increment a character from 97 to 122 to print out all lowercase characters. Sometimes this actually is useful.

你可以做像 char c = 97; 这将打印为 a. 您可以执行一些操作,例如将字符从 97 增加到 122 以打印出所有小写字符。有时这实际上很有用。