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程序来访问编码技能。

Java中的字符串程序 (String Programs in Java)

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表达式 , 功能接口等。

如何在字符串中获取不同的字符及其数量? (How to get distinct characters and their count in a String?)

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

编写一个Java程序来反转字符串? (Write a java program to reverse a String?)

There are many ways to reverse a String. Some of the common ones are:

有很多反向字符串的方法。 一些常见的是:

  • StringBuilder/StringBuffer reverse() methodStringBuilder / StringBuffer reverse()方法
  • Using char/byte array and traverse in reverse direction and populate the result string使用char / byte数组并反向遍历并填充结果字符串

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

如何检查一个字符串是否是回文? (How to check if a String is Palindrome?)

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

如何从输入String中删除所有出现的给定字符? (How to remove all occurrences of a given character from input String?)

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

如何通过编程证明String是不可变的? (How to prove String is immutable programatically?)

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 s1String s2 = s1; //s2 is also having the same reference to "Java" in the poolSystem.out.println(s1 == s2); // proof that s1 and s2 have same references1 = "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 referenceSystem.out.println(s1 == s2); System.out.println(s2); // prints "Java" supporting the fact that original String value is unchanged, hence String is immutable}}

编写一个程序来计算字符串中的单词数? (Write a program to count number of words in a String?)

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 spacesString trimmedLine = line.trim();int count = trimmedLine.isEmpty() ? 0 : trimmedLine.split("\\s+").length;System.out.println(count);}}

编写程序以检查是否用相同的字符创建了两个字符串? (Write a program to check if two Strings are created with same characters?)

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

读取两个String用户输入,并检查第一个是否包含第二个? (Read two String user input and check if first contains second?)

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

如何在不使用第三个变量的情况下交换两个字符串? (How to swap two Strings without using a third variable?)

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+s2container.setSecondString(container.getFirstString().substring(0, container.getFirstString().length()-container.getSecondString().length())); // s2=s1container.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;}@Overridepublic 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

编写程序以从输入String中找出第一个非重复字符? (Write a program to find out first non repeated character from input String?)

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 founddiscardedChars.add(c);break;} else if (j == chars.length - 1) { // no match found till endreturn c;}}}return null;}}

提供两种方法来检查字符串是否仅包含数字? (Provide two ways to check if a String contains only digits?)

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

如何对字符串执行深度复制? (How to perform Deep Copy for 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中详细信息。

GitHub Repository.GitHub Repository下载示例。

翻译自: https://www.journaldev.com/20819/string-programs-in-java

Java中的字符串程序相关推荐

  1. Java中的字符串驻留

    转自:http://www.cdtarena.com/javapx/201307/9088.html 最近在工作的时候,一句再正常不过的代码String a = "hello" + ...

  2. 图说:为什么Java中的字符串被定义为不可变的

    转载自 图说:为什么Java中的字符串被定义为不可变的 字符串,想必大家最熟悉不过了,通常我们在代码中有几种方式可以创建字符串,比如:String s = "Hollis";这时, ...

  3. [转载] Java中的字符串处理

    参考链接: Java中的StringBuffer appendCodePoint()方法以及示例 JDK8在线Api中文手册 JDK8在线Api英文手册 Java中的字符串处理 1.1 String类 ...

  4. 怎么比较字符串java_如何在Java中比较字符串?

    在本文中,优锐课将带你学习如何比较字符串以及使用等于(=)运算符比较字符串时发生的问题. 介绍 字符串是Java中的特殊类.我们在Java程序中定期使用String,因此比较两个字符串是Java中的一 ...

  5. Java中的字符串串联

    String Concatenation in java is very common. Being a Java developer, you are aware that every once i ...

  6. java输入一串字符串反转_反转Java中的字符串

    java输入一串字符串反转 Reverse a String in java is a good coding related interview question. I have seen inte ...

  7. java 字符串驻留_【Java中的字符串驻留】

    最近在工作的时候,一句再正常不过的代码String a = "hello" + "world";被改成了new StringBuilder().append(& ...

  8. java里面string什么意思_「Java基础知识」Java中的字符串是什么

    原标题:「Java基础知识」Java中的字符串是什么 字符串顾名思义就是一些字符组合在一起组成的一串数据,称作字符串,在Java中字符串用双引号包围起来,格式为String string = &quo ...

  9. 字符串压缩 java_如何在Java中压缩字符串?

    如何在Java中压缩字符串? 我使用GZIPOutputStream或ZIPOutputStream压缩字符串(我的2222235278130938882小于20),但压缩结果比原始字符串长. 在某个 ...

最新文章

  1. AIX系统日志学习笔记之一
  2. 嵌入式学习笔记之一:嵌入式linux中混合编译入门
  3. 怎么暂时关闭网站php,WordPress怎么临时关闭网站进行维护
  4. mysql 失效转移_MySQL基于MHA的FailOver过程
  5. Pytest参数选项自由执行测试用例详解(二)
  6. 中国人写的编译器-值得看看
  7. C++ Templates之模板元编程
  8. JSP:src路径里有中文,产生乱码问题
  9. 在windows 服务中 调打印_Windows打印后台处理程序漏洞(CVE20201048)
  10. 命令窗 创建vue 项目过程
  11. 百度工程师带来干货分享,助你转型AI应用工程师!
  12. RK3288_Android7.1调试uart串口屏
  13. java中utf8转成gbk,java中GBK转UTF-8乱码的解决方法
  14. java b2b2c 多商户 电商 源码,整套可运行
  15. haproxy编译安装以及配置文档介绍
  16. Hudi-通过Hive查询hudi表数据
  17. 粒子群算法组卷_概率表示的二进制粒子群算法在组卷中的应用
  18. 万年历单片机c语言,c51单片机万年历的c程序
  19. 互动媒体——随及行为以及运动学
  20. unity之跳一跳(完整版)

热门文章

  1. [ocUI日记]UIwindow和UIview
  2. JAVA 自定义注解在自动化测试中的使用
  3. Windwows7 下安装mysql5
  4. Python程序提示出现File stdin,line 1错误解决方法
  5. [转载] 用python统计中文字符数_使用Python统计字符串中各种字符的个数
  6. 从今天开始 好好规划自己
  7. Java之戳中痛点 - (5)switch语句break不能忘以及default不同位置的用法
  8. Winform 中 dataGridView 导出到Excel中的方法总结
  9. android重要的对象
  10. 安装 Visual Studio Async CTP