赞
踩
String is the most widely used class in java programming. That’s why String programs are used in java interviews to access the coding skills.
字符串是Java编程中使用最广泛的类。 这就是为什么在Java采访中使用String程序来访问编码技能。
Here I am providing some string programs in java to help you in brushing up your coding skills. Please try to solve these questions yourself before checking the answers to learn in a better way.
在这里,我提供了一些Java字符串程序来帮助您提高编码技巧。 请尝试自己解决这些问题,然后再检查答案以更好地学习。
I am trying to use all the latest functionalities introduced in java, such as Stream, lambda expressions, functional interfaces etc.
我正在尝试使用Java中引入的所有最新功能,例如Stream , lambda表达式 , 功能接口等。
- package com.journaldev.java.string;
-
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.stream.Collectors;
-
- public class DistinctCharsCount {
-
- public static void main(String[] args) {
-
- printDistinctCharsWithCount("abc");
- printDistinctCharsWithCount("abcab3");
- printDistinctCharsWithCount("hi there, i am pankaj");
- }
-
- private static void printDistinctCharsWithCount(String input) {
- Map<Character, Integer> charsWithCountMap = new HashMap<>();
-
- // using Map merge method from Java 8
- for (char c : input.toCharArray())
- charsWithCountMap.merge(c, 1, Integer::sum);
- System.out.println(charsWithCountMap);
-
- // another way using latest Java enhancements and no for loop, a bit complex though
- List<Character> list = input.chars().mapToObj(c -> (char) c).collect(Collectors.toList());
-
- list.stream().forEach(c -> charsWithCountMap.merge(c, 1, Integer::sum));
-
- System.out.println(charsWithCountMap);
-
- }
-
- }

There are many ways to reverse a String. Some of the common ones are:
有很多反向字符串的方法。 一些常见的是:
reverse() method StringBuilder / StringBuffer reverse()方法 However if you are not sure of input String content, always use StringBuilder built-in reverse() method. Because using char and byte array may produce unwanted results. I have provided a complete explanation for this in Reverse a String in Java.
但是,如果不确定输入的String内容,请始终使用StringBuilder内置的reverse()方法。 因为使用char和byte数组可能会产生不需要的结果。 我已经在Java中反向字符串中提供了完整的解释。
- package com.journaldev.java.string;
-
- public class ReverseAString {
-
- public static void main(String[] args) {
-
- reverseInputString("abc");
- reverseInputString("ç©∆˙¨˚ø"); //special chars
- }
-
- private static void reverseInputString(String input) {
- StringBuilder sb = new StringBuilder(input);
- String result = sb.reverse().toString();
- System.out.println(result);
- }
-
- }

A palindrome string is one whose reverse is also same string. So we can reverse the input string and check if both strings are equal for this. Or we can be smart and use the String charAt(int index) method to check for palindrome string.
回文字符串是反向字符串也相同的字符串。 因此,我们可以反转输入字符串,并检查两个字符串是否相等。 或者我们可以很聪明,使用String charAt(int index)方法检查回文字符串。
- package com.journaldev.java.string;
-
- public class PalindromeString {
-
- public static void main(String[] args) {
-
- checkPalindromeString("abc");
- checkPalindromeString("abcba");
- checkPalindromeString("ç∂©∂ç");
- }
-
- private static void checkPalindromeString(String input) {
- boolean result = true;
- int length = input.length();
- for(int i=0; i < length/2; i++) {
- if(input.charAt(i) != input.charAt(length-i-1)) {
- result = false;
- break;
- }
- }
- System.out.println(input + " is palindrome = "+result);
-
- }
-
- }

There is no remove function in the String class, but we can use replaceAll() in this case. Here is the simple program showing how to do it.
String类中没有remove函数,但是在这种情况下,我们可以使用replaceAll() 。 这是显示如何执行此操作的简单程序。
- package com.journaldev.java.string;
-
- public class RemoveCharFromString {
-
- public static void main(String[] args) {
-
- removeCharFromString("abcbcdjfkd", 'c');
- removeCharFromString("Pankaj", 'a');
- removeCharFromString("ç∂©∂ç", '©');
-
- }
-
- private static void removeCharFromString(String input, char c) {
- String result = input.replaceAll(String.valueOf(c), "");
- System.out.println(result);
- }
-
- }

We know that String is immutable in java, however new developers still get confused with this.
我们知道String在Java中是不可变的 ,但是新开发人员仍然对此感到困惑。
Let’s try to understand the reason for this confusion.
让我们尝试了解造成这种混乱的原因。
- String s1 = "Java";
-
- s1 = "Python";
In above code snippet, we can say that s1 value got changed and it’s a String object. So how can we say that String is immutable?
在上面的代码片段中,我们可以说s1值已更改,它是一个String对象。 那么我们怎么能说String是不可变的呢?
The most important point to understand is how Strings get created in java. When we create a String using string literal, it doesn’t change the value of original String. It creates a new String in the string pool and change the reference of the variable. So original string value is never changed and that’s why Strings are immutable.
要理解的最重要一点是如何在Java中创建字符串。 当我们使用字符串文字创建一个String时,它不会更改原始String的值。 它在字符串池中创建一个新的String并更改变量的引用。 因此,原始字符串值永远不会改变,这就是字符串不可更改的原因。
Below program proofs our statement, read out the comments for proper understanding the concept.
在程序下面证明我们的陈述,读出注释以正确理解概念。
- package com.journaldev.java.string;
-
- public class StringImmutabilityTest {
-
- public static void main(String[] args) {
-
- String s1 = "Java"; // "Java" String created in pool and reference assigned to s1
-
- String s2 = s1; //s2 is also having the same reference to "Java" in the pool
-
- System.out.println(s1 == s2); // proof that s1 and s2 have same reference
-
- s1 = "Python";
- //s1 value got changed above, so how String is immutable?
-
- //well, in above case a new String "Python" got created in the pool
- //s1 is now referring to the new String in the pool
- //BUT, the original String "Java" is still unchanged and remains in the pool
- //s2 is still referring to the original String "Java" in the pool
-
- // proof that s1 and s2 have different reference
- System.out.println(s1 == s2);
-
- System.out.println(s2);
- // prints "Java" supporting the fact that original String value is unchanged, hence String is immutable
-
- }
-
- }

The simple solution to this program seems to be input.split(" ").length but this won’t work if your string is not properly formatted and it contains leading and trailing spaces, duplicate multiple spaces and tabs.
该程序的简单解决方案似乎是input.split(" ").length但是如果您的字符串格式不正确并且包含前导和尾随空格,重复多个空格和制表符,则此方法将无效。
Luckily String split() function takes regular expression as argument and we can use it to count the number of words in a string.
幸运的是, String split()函数使用正则表达式作为参数,我们可以使用它来计算字符串中的单词数。
- package com.journaldev.java.string;
-
- public class CountNumberOfWordsInString {
-
- public static void main(String[] args) {
-
- countNumberOfWords("My name is Pankaj");
- countNumberOfWords("I Love Java Programming");
- countNumberOfWords(" This is not properly formatted line ");
-
- }
-
- private static void countNumberOfWords(String line) {
- //System.out.println(line.split(" ").length); //won't work with tabs and multiple spaces
-
- String trimmedLine = line.trim();
- int count = trimmedLine.isEmpty() ? 0 : trimmedLine.split("\\s+").length;
-
- System.out.println(count);
- }
-
- }

First of all we will have to create a Set of characters from the input Strings. Then use Set equals() method to check if they contains the same characters or not. Here is a simple program to check if two strings are created with same characters.
首先,我们必须根据输入的字符串创建一组字符。 然后使用Set equals()方法检查它们是否包含相同的字符。 这是一个简单的程序,用于检查是否使用相同的字符创建了两个字符串。
- package com.journaldev.java.string;
-
- import java.util.Set;
- import java.util.stream.Collectors;
-
- public class CheckSameCharsInString {
-
- public static void main(String[] args) {
- sameCharsStrings("abc", "cba");
- sameCharsStrings("aabbcc", "abc");
- sameCharsStrings("abcd", "abc");
- sameCharsStrings("11", "1122");
- sameCharsStrings("1122", "11");
- }
-
- private static void sameCharsStrings(String s1, String s2) {
-
- Set<Character> set1 = s1.chars().mapToObj(c -> (char) c).collect(Collectors.toSet());
- Set<Character> set2 = s2.chars().mapToObj(c -> (char) c).collect(Collectors.toSet());
- System.out.println(set1.equals(set2));
- }
-
- }

This is a simple program and we can use String contains() method to check if specified string is part of this string. However we will have to use Scanner class to read user inputs.
这是一个简单的程序,我们可以使用String contains()方法检查指定的字符串是否是该字符串的一部分。 但是,我们将不得不使用Scanner类来读取用户输入。
- package com.journaldev.java.string;
-
- import java.util.Scanner;
-
- public class StringContainsSubstring {
-
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- System.out.println("Enter First String:");
- String s1 = scanner.nextLine();
-
- System.out.println("Enter Second String:");
- String s2 = scanner.nextLine();
-
- scanner.close();
-
- boolean result = stringContainsSubstring(s1, s2);
- System.out.println(s1+" contains "+s2+" = "+result);
- }
-
- private static boolean stringContainsSubstring(String string, String substring) {
- boolean result = false;
- result = string.contains(substring);
- return result;
- }
-
- }

Here is a sample output of above program:
这是上述程序的示例输出:
- Enter First String:
- Pankaj
- Enter Second String:
- an
- Pankaj contains an = true
We can do it using String substring() method. Here is a simple code snippet to showcase this:
我们可以使用String substring()方法做到这一点。 这是一个简单的代码片段来展示这一点:
- String s1 = "abc";
- String s2 = "def";
-
- s1 = s1.concat(s2);
- s2 = s1.substring(0,s1.length()-s2.length());
- s1 = s1.substring(s2.length());
What if we have to write a function to do this? Since String is immutable, the change in values of the String references in the method will be gone as soon as the method ends. Also we can’t return multiple objects from a method in java. So we will have to create a Container to hold the input strings and then perform the above logic in the method. Below code shows how this can be done, although it might look complex but the logic is same as above.
如果我们必须编写一个函数来执行此操作怎么办? 由于String是不可变的,因此方法结束后,该方法中String引用的值更改将消失。 同样,我们不能从java中的方法返回多个对象。 因此,我们将必须创建一个容器来容纳输入字符串,然后在方法中执行上述逻辑。 下面的代码显示了如何完成此操作,尽管看起来很复杂,但逻辑与上面相同。
- package com.journaldev.java.string;
-
- import java.util.Scanner;
-
- public class SwapTwoStrings {
-
- public static void main(String[] args) {
-
- Container container = new Container();
- Scanner scanner = new Scanner(System.in);
- System.out.println("Enter First String:");
- container.setFirstString(scanner.nextLine());
-
- System.out.println("Enter Second String:");
- container.setSecondString(scanner.nextLine());
- scanner.close();
- System.out.println(container);
- container = swapStrings(container);
- System.out.println(container);
- }
-
- private static Container swapStrings(Container container) {
- container.setFirstString(container.getFirstString().concat(container.getSecondString())); //s1 = s1+s2
- container.setSecondString(container.getFirstString().substring(0, container.getFirstString().length()-container.getSecondString().length())); // s2=s1
- container.setFirstString(container.getFirstString().substring(container.getSecondString().length()));
- return container;
- }
-
- }
-
- class Container{
- private String firstString;
- private String secondString;
-
- public String getFirstString() {
- return firstString;
- }
- public void setFirstString(String firstString) {
- this.firstString = firstString;
- }
- public String getSecondString() {
- return secondString;
- }
- public void setSecondString(String secondString) {
- this.secondString = secondString;
- }
-
- @Override
- public String toString() {
- return "First String = "+firstString+", Second String = "+secondString;
- }
- }

Sample Output:
样本输出:
- Enter First String:
- Java
- Enter Second String:
- Python
- First String = Java, Second String = Python
- First String = Python, Second String = Java
- package com.journaldev.java.string;
-
- import java.util.ArrayList;
- import java.util.List;
-
- public class FindNonRepeatingChar {
-
- public static void main(String[] args) {
-
- System.out.println(printFirstNonRepeatingChar("abcaabcdedxy"));
- System.out.println(printFirstNonRepeatingChar("abca"));
- System.out.println(printFirstNonRepeatingChar("aaa"));
-
- }
-
- private static Character printFirstNonRepeatingChar(String string) {
- char[] chars = string.toCharArray();
-
- List<Character> discardedChars = new ArrayList<>();
-
- for (int i = 0; i < chars.length; i++) {
- char c = chars[i];
-
- if (discardedChars.contains(c))
- continue;
-
- for (int j = i + 1; j < chars.length; j++) {
- if (c == chars[j]) { // match found
- discardedChars.add(c);
- break;
- } else if (j == chars.length - 1) { // no match found till end
- return c;
- }
- }
- }
- return null;
- }
-
- }

We can use regular expression to check if a String is numeric or not. Another way is to parse it to Long and if it’s a non numeric string then it will throw NumberFormatException.
我们可以使用正则表达式来检查String是否为数字。 另一种方法是将其解析为Long,如果它是非数字字符串,则它将引发NumberFormatException 。
- package com.journaldev.java.string;
-
- public class CheckIfStringContainsDigitsOnly {
-
- public static void main(String[] args) {
- digitsOnlyString("111");
- digitsOnlyString("111a 1");
- digitsOnlyString("111 222");
- digitsOnlyString("111L");
-
- }
-
- private static void digitsOnlyString(String string) {
- if(string.matches("\\d+")) System.out.println("Digit Only String ::"+string);
-
- try {
- long l = Long.parseLong(string);
- System.out.println("Digit Only String ::"+string);
- }catch(Exception e){
- System.out.println("Non Digit Only String ::"+string);
- }
-
- }
-
- }

String is immutable, so we don’t need to worry about deep copy or shallow copy. We can simply use assignment operator (=) to copy one string to another. Read more details at Java String copy.
字符串是不可变的,因此我们不必担心深层副本或浅层副本。 我们可以简单地使用赋值运算符(=)将一个字符串复制到另一个字符串。 在Java String copy中阅读更多详细信息。
翻译自: https://www.journaldev.com/20819/string-programs-in-java
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。