Maison > Java > javaDidacticiel > le corps du texte

【JAVA实例】字符串搜索、反转、删除

黄舟
Libérer: 2017-02-07 10:49:20
original
1205 Les gens l'ont consulté

Java 实例 - 字符串搜索

以下实例使用了  String  类的  indexOf() 方法在字符串中查找子字符串出现的位置,如过存在返回字符串出现的位置(第一位为0),如果不存在返回 -1:

//SearchStringEmp.java 文件public class SearchStringEmp{
   public static void main(String[] args) {
      String strOrig = "Hello readers";
      int intIndex = strOrig.indexOf("Hello");
      if(intIndex == - 1){
         System.out.println("Hello not found");
      }else{
         System.out.println("Found Hello at index "
         + intIndex);
      }
   }}
Copier après la connexion

以上代码实例输出结果为:

Found Hello at index 0
Copier après la connexion

字符串反转

以下实例演示了如何使用 Java 的反转函数 reverse() 将字符串反转:

public class StringReverseExample{
   public static void main(String[] args){
      String string="abcdef";
      String reverse = new StringBuffer(string).
      reverse().toString();
      System.out.println("nString before reverse:
      "+string);
      System.out.println("String after reverse:
      "+reverse);
   }}
Copier après la connexion

以上代码实例输出结果为:

String before reverse:abcdef
String after reverse:fedcba
Copier après la connexion

▎ 删除字符串中的一个字符

以下实例中我们通过字符串函数 substring() 函数来删除字符串中的一个字符,我们将功能封装在 removeCharAt 函数中。

实例代码如下:

//Main.java 文件public class Main {
   public static void main(String args[]) {
      String str = "this is Java";
      System.out.println(removeCharAt(str, 3));
   }
   public static String removeCharAt(String s, int pos) {
      return s.substring(0, pos) + s.substring(pos + 1);
   }}
Copier après la connexion

以上代码实例输出结果为:

thi is Java
Copier après la connexion

以上就是【JAVA实例】字符串搜索、反转、删除的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!