Как взять первый элемент строки java
Перейти к содержимому

Как взять первый элемент строки java

  • автор:

Manipulating Characters in a String

The String class has a number of methods for examining the contents of strings, finding characters or substrings within a string, changing case, and other tasks.

Getting Characters and Substrings by Index

You can get the character at a particular index within a string by invoking the charAt() accessor method. The index of the first character is 0, while the index of the last character is length()-1 . For example, the following code gets the character at index 9 in a string:

Indices begin at 0, so the character at index 9 is 'O', as illustrated in the following figure:

If you want to get more than one consecutive character from a string, you can use the substring method. The substring method has two versions, as shown in the following table:

The substring Methods in the String Class

Method Description
String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex — 1 .
String substring(int beginIndex) Returns a new string that is a substring of this string. The integer argument specifies the index of the first character. Here, the returned substring extends to the end of the original string.

The following code gets from the Niagara palindrome the substring that extends from index 11 up to, but not including, index 15, which is the word "roar":

Other Methods for Manipulating Strings

Here are several other String methods for manipulating strings:

Other Methods in the String Class for Manipulating Strings

Method Description
String[] split(String regex)
String[] split(String regex, int limit)
Searches for a match as specified by the string argument (which contains a regular expression) and splits this string into an array of strings accordingly. The optional integer argument specifies the maximum size of the returned array. Regular expressions are covered in the lesson titled "Regular Expressions."
CharSequence subSequence(int beginIndex, int endIndex) Returns a new character sequence constructed from beginIndex index up until endIndex — 1.
String trim() Returns a copy of this string with leading and trailing white space removed.
String toLowerCase()
String toUpperCase()
Returns a copy of this string converted to lowercase or uppercase. If no conversions are necessary, these methods return the original string.

Searching for Characters and Substrings in a String

Here are some other String methods for finding characters or substrings within a string. The String class provides accessor methods that return the position within the string of a specific character or substring: indexOf() and lastIndexOf() . The indexOf() methods search forward from the beginning of the string, and the lastIndexOf() methods search backward from the end of the string. If a character or substring is not found, indexOf() and lastIndexOf() return -1.

The String class also provides a search method, contains , that returns true if the string contains a particular character sequence. Use this method when you only need to know that the string contains a character sequence, but the precise location isn't important.

The following table describes the various string search methods.

The Search Methods in the String Class

Method Description
int indexOf(int ch)
int lastIndexOf(int ch)
Returns the index of the first (last) occurrence of the specified character.
int indexOf(int ch, int fromIndex)
int lastIndexOf(int ch, int fromIndex)
Returns the index of the first (last) occurrence of the specified character, searching forward (backward) from the specified index.
int indexOf(String str)
int lastIndexOf(String str)
Returns the index of the first (last) occurrence of the specified substring.
int indexOf(String str, int fromIndex)
int lastIndexOf(String str, int fromIndex)
Returns the index of the first (last) occurrence of the specified substring, searching forward (backward) from the specified index.
boolean contains(CharSequence s) Returns true if the string contains the specified character sequence.

Replacing Characters and Substrings into a String

The String class has very few methods for inserting characters or substrings into a string. In general, they are not needed: You can create a new string by concatenation of substrings you have removed from a string with the substring that you want to insert.

The String class does have four methods for replacing found characters or substrings, however. They are:

Methods in the String Class for Manipulating Strings

Method Description
String replace(char oldChar, char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String replace(CharSequence target, CharSequence replacement) Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
String replaceAll(String regex, String replacement) Replaces each substring of this string that matches the given regular expression with the given replacement.
String replaceFirst(String regex, String replacement) Replaces the first substring of this string that matches the given regular expression with the given replacement.

An Example

The following class, Filename , illustrates the use of lastIndexOf() and substring() to isolate different parts of a file name.

Here is a program, FilenameDemo , that constructs a Filename object and calls all of its methods:

And here's the output from the program:

As shown in the following figure, our extension method uses lastIndexOf to locate the last occurrence of the period (.) in the file name. Then substring uses the return value of lastIndexOf to extract the file name extension — that is, the substring from the period to the end of the string. This code assumes that the file name has a period in it; if the file name does not have a period, lastIndexOf returns -1, and the substring method throws a StringIndexOutOfBoundsException .

Also, notice that the extension method uses dot + 1 as the argument to substring . If the period character (.) is the last character of the string, dot + 1 is equal to the length of the string, which is one larger than the largest index into the string (because indices start at 0). This is a legal argument to substring because that method accepts an index equal to, but not greater than, the length of the string and interprets it to mean "the end of the string."

Получить первые n символов строки в Java

В этом посте речь пойдет о том, как получить первый n символы строки в Java, где n является неотрицательным целым числом.

1. Использование substring() метод

Чтобы получить первый n символов строки, мы можем передать начальный индекс как 0 и конечный индекс как n к substring() метод. Обратите внимание, что substring() метод возвращает IndexOutOfBoundsException если конечный индекс больше длины строки. Это можно обработать с помощью тернарного оператора, как показано ниже:

Get string character by index

I know how to work out the index of a certain character or number in a string, but is there any predefined method I can use to give me the character at the nth position? So in the string «foo», if I asked for the character with index 0 it would return «f».

Note — in the above question, by «character» I don’t mean the char data type, but a letter or number in a string. The important thing here is that I don’t receive a char when the method is invoked, but a string (of length 1). And I know about the substring() method, but I was wondering if there was a neater way.

charAt() in Java – How to Use the Java charAt() Method

Ihechikara Vincent Abba

Ihechikara Vincent Abba

charAt() in Java – How to Use the Java charAt() Method

The charAt() method in Java returns the char value of a character in a string at a given or specified index.

In this article, we’ll see how to use the charAt() method starting with it’s syntax and then through a few examples/use cases.

How to Use the Java charAt() Method

Here is what the syntax for the charAt() method looks like:

Note that the characters returned from a string using the charAt() method have a char data type. We’ll see how this affects concatenation of the returned values later in the article.

Now let’s see some examples.

In the code above, our string – stored in a variable called greetings – says «Hello World». We used the charAt() method to get the character at index 0 which is H.

The first character will always have an index of 0, the second an index of 1, and so on. The space between substrings also counts as an index.

In the next example, we’ll see what happens when we try to concatenate the different characters returned. Concatenation means joining two or more values together (in most cases, this term is used for joining characters or substrings in a string).

Using the charAt() method, we got the characters at index 0, 4, 9 and 10 which are H, o, l and d, respectively.

We then tried to print and concatenate these characters: System.out.println(ch1 + ch2 + ch3 + ch4); .

But instead of getting «Hold» returned to us, we got 391. This happened because the returned values are no longer strings but have a data type of char . So when we concatenate them, the interpreter adds their ASCII value instead.

H has an ASCII value of 72, o has a value of 111, l has a value of 108, and d has a value of 100. When we add them together, we get 391 which was returned in the last example.

StringIndexOutOfBoundsException Error

When we pass in an index number that exceeds the number of characters in our string, we’d get the StringIndexOutOfBoundsException error in the console.

This error also applies to using negative indexing which is not supported in Java. In programming languages like Python that have support for negative indexing, passing in -1 will give you the last character or value in a data set, similar to how 0 always returns the first character.

Here is an example:

In the code above, we passed in an index of 20: char ch1 = greetings.charAt(20); which exceeds the number of characters in our greetings variable – so we got an error thrown at us. You can see the error message commented out in the code block above.

Similarly, if we pass in a negative value like this: char ch1 = greetings.charAt(-1); , we would get a similar error.

Conclusion

In this article, we learned how to use the charAt() method in Java. We saw how to return characters in a string based on their index number and what happens when we concatenate these characters.

Lastly, we talked about some of the instances where we would get an error response while using the charAt() method in Java.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *