当前位置: 移动技术网 > IT编程>开发语言>Java > Java探索之string字符串的应用代码示例

Java探索之string字符串的应用代码示例

2019年07月19日  | 移动技术网IT编程  | 我要评论

string类中提供了丰富的用于操作字符串的方法。

int indexof(string str)

该方法用于返回当给定字符串在当前字符串中的位置,若当前字符串不包含给定字符串则返回-1。

重载的方法

int indexof(string str,int formindex),从指定下标处(包含)查询子串,返回返回当给定字符串在当前字符串中的位置,若当前字符串不包含给定字符串则返回-1。

用自己的算法实现startswith和endswith功能。

package com.hz.practice;
/**
 * 1. 用自己的算法实现startswith和endswith功能。
 * @author ztw
 *
 */
public class practice01 {
  public static void main(string[] args) {
    string str = "qwewrewr";
//   boolean temp = str.endswith("r");
//   system.out.println(temp);
    /*
     * startswith
     */
    char[] arr = str.tochararray();
    char c = 'r';
    if(arr[0]==c){
      system.out.println("true");
    }else{
      system.out.println("false");
    }
    /*
     * endswith
     */
    if(arr[arr.length-1]==c){
      system.out.println("true");
    }else{
      system.out.println("false");
    }
  }
}

输出结果:

false 
true

2.采用字符的移位方式实现字符文本加密解密。

package com.hz.practice;
import java.util.scanner;
/**
 * 2.采用字符的移位方式实现字符文本加密解密。
 * @author ztw
 *
 */
public class practice02 {
  public static void main(string[] args) {
    system.out.println("请输入一个字符串");
    scanner sc =new scanner(system.in);
    string str1 = new string();
    str1=sc.nextline();    
    system.out.println(str1.replaceall("a", "1.")
        .replaceall("b", "2.").replaceall("c", "3.")
        .replaceall("d", "4.").replaceall("e", "5.")
        .replaceall("f", "6.").replaceall("g", "7.")
        .replaceall("h", "8.").replaceall("i", "9.")
        .replaceall("j", "10.").replaceall("k", "11.")
        .replaceall("l", "12.").replaceall("m", "13.")
        .replaceall("n", "14.").replaceall("o", "15.")
        .replaceall("p", "16.").replaceall("q", "17.")
        .replaceall("r", "18.").replaceall("s", "19.")
        .replaceall("t", "20.").replaceall("u", "21.")
        .replaceall("v", "22.").replaceall("w", "23.")
        .replaceall("x", "24.").replaceall("y", "25.")
        .replaceall("z", "26."));
  }
}

输出结果:

请输入一个字符串 
asdsddffg 
1.19.4.19.4.4.6.6.7.

3.验证是随机生成4位验证码,由用户输入并否输入正确, 如果输入错误就生成新的验证码让用户重新输入,最多输入5次!

package com.hz.practice;
import java.util.random;
import java.util.scanner;
/**
 * 3.验证是随机生成4位验证码,由用户输入并否输入正确,
 * 如果输入错误就生成新的验证码让用户重新输入,最多输入5次
 * @author ztw
 *
 */
public class practice03 {
  public static void main(string[] args) {
    string str="0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
    char[]arr=new char[4];//定义一个长度是4的char型数组
    random sj=new random();
    system.out.println("验证码是:");
    for(int i=0;i<4;i++)
    {
      arr[i]=str.charat(sj.nextint(61));//从str中随机截取4个单个字符并赋值给arr这个数组存放
    }
    system.out.println(arr);
    scanner sc=new scanner(system.in);
    system.out.println("请输入验证码");
    string a=new string(arr);//把数组转换成字符串
    //定义输入次数
    for(int j=0;j<5;j++)
    {
      if(sc.nextline().equals(a))
      {
        system.out.println("验证码输入正确");
      }
      else
      {
        system.out.println("验证码输入有误,请重新输入");
        if(j<=3)
        {
          system.out.print("请输入验证码");
          for(int i=0;i<4;i++)
          {
            arr[i]=str.charat(sj.nextint(61));//从str中随机截取4个单个字符并赋值给arr这个数组存放
          }
          system.out.println(arr);
          a=new string (arr);
        }
        else
        {
          system.out.println("输入有误,对不起,5次机会已用完");
        }
      }
    }
  }
}

输出结果:

验证码是: 
ava8 
请输入验证码 
ava8 
验证码输入正确
package com.hz.practice;

/**
 * 4.获取一个字符串在另一个字符串中出现的次数
  思路:
  1.定义一个计数器。
  2.获取子串第一次出现的位置
  3.从第一次出现的位置后剩余的字符串中继续获取子串出现的位置,每获取一次计数器加1
  4,当获取不到时,计数完成
 * @author ztw
 *
 */
public class practice04 {

  public static void main(string[] args) {

    string str1 = "asdasdas";
    string str2 = "as";
    //1.定义一个计数器。
    int total = 0;
    for (string temp = str1; temp!=null && 
        temp.length()>=str2.length();) {
      //2.获取子串第一次出现的位置
      if(temp.indexof(str2) == 0){
        //3.从第一次出现的位置后剩余的字符串中继续获取子串出现的位置,每获取一次计数器加1
        total ++;
      }
      temp = temp.substring(1);
      system.out.print(temp+", ");
    }
    //4,当获取不到时,计数完成
    system.out.println("计数完成:"+total);
  }
}

输出结果:

sdasdas, dasdas, asdas, sdas, das, as, s, 计数完成:3
package com.hz.practice;
/**
 * 5.获取两个子串中最大相同子串
   思路:
   1.将短的哪个子串按照长度递减的方式获取到
   2.将每次获取到的子串去长串中判断是否包含,如果包含,已经找到
 * @author ztw
 *
 */
public class practice05 {
   public static string getmaxsubstring(string s1,string s2) { 
      string max = "",min = ""; 
      max = (s1.length()>s2.length())?s1: s2; 
      min = (max==s1)?s2: s1;    
//     sop("max="+max+"...min="+min); 
      for(int x=0; x<min.length(); x++) 
      { 
        for(int y=0,z=min.length()-x; z!=min.length()+1; y++,z++) 
        { 
          string temp = min.substring(y,z);         
          sop(temp); 
          if(max.contains(temp))//if(s1.indexof(temp)!=-1) 
            return temp; 
        } 
      } 
      return ""; 
    } 
    public static void main(string[] args)  
    { 
      string s1 = "ab"; 
      string s2 = "cvhellobnm"; 
      sop(getmaxsubstring(s2,s1)); 
    } 
    public static void sop(string str) 
    { 
      system.out.print(str+", "); 
    } 
}

输出结果:

ab, a, b, b,
package com.hz.practice;
import java.util.scanner;
/**
 * 6、写一个方法判断一个字符串是否对称
 * @author ztw
 *
 */
public class practice06 {
  public static void main(string[] args){
    scanner input = new scanner(system.in);
    string str = input.next();//接收任意字符串
    isok1(str);            
}
  /**
   * 判断字符串是否对称的方法(一)
   * 通过取取索引对应值来进行一一比对
   * @param str
   */
  public static void isok1(string str){
      boolean result = true;
      int count =(str.length()-1)/2;
      for (int x=0;x<=count;x++ ){
          if(str.charat(x)!=str.charat(str.length()-1-x)){
              result = false;
              break;
          }
      }
      if(!result)
          system.out.println("该字符串是不对称的");
      else
          system.out.println("该字符串是对称的");
  }
  /*
   * public static void main(string[] args){
        scanner input = new scanner(system.in);
      string str = input.next();//接收任意字符串
          if (isok2(str)==true) {
            system.out.println("真,对称!");
        }else{
            system.out.println("假,不对称!");
        }
    }
    /**
     * 方法二
     * 通过string加强类中的取反方法reverse获取其逆向值
     * 再与原字符串相比是否相等!
     * 等于则返回true,否则false
     * @param str
     * @return
     */
  /*
    public static boolean isok2(string str){
        stringbuffer sb = new stringbuffer(str);
        string str2 = sb.reverse().tostring();
        return str.equals(str2);
    }
   */
}

输出结果:

asdsa 
该字符串是对称的
package com.hz.practice;
/**
 * 
  9、编写一个程序,将下面的一段文本中的各个单词的字母顺序翻转,
  “to be or not to be",将变成"ot eb ro ton ot eb."。
 * @author ztw
 *
 */
public class practice09 {
  public static void main(string[] args) {
    string str = "to be or not to be";
    string[] str2 = str.split(" ");
    for (int i = 0; i < str2.length; i++) {
      char[] ci = str2[i].tochararray();
      system.out.print(" ");
      for (int j = ci.length-1; j >= 0 ; j--) {
        system.out.print(ci[j]);
      }
    }
  }
}
package com.hz.practice;
/**
 * 10、已知字符串:"this is a test of java". 
  按要求执行以下操作:
  (1) 统计该字符串中字母s出现的次数
  (2) 取出子字符串"test"
  (3) 用多种方式将本字符串复制到一个字符数组char[] str中.
  (4) 将字符串中每个单词的第一个字母变成大写, 输出到控制台。
  (5) 用两种方式实现该字符串的倒叙输出。(用stringbuffer和for循环方式分别实现)
  (6) 将本字符串转换成一个字符串数组,要求每个数组元素都是一个有意义的额英文单词,并输出到控制台
 * @author ztw
 *
 */
public class practice10 {
  public static void main(string[] args) {
    string str = "this is a test of java";
//   (1) 统计该字符串中字母s出现的次数
    int count = 0;
    for (int i = 0; i < str.length(); i++) {
      if(str.charat(i)=='s'){
        count++;
      }
    }
    system.out.println("字符串中字母s出现的次数:"+count);
//   (2) 取出子字符串"test"
    string str2 = (string) str.subsequence(10, 14);
    system.out.println(str2);
//   (3) 用多种方式将本字符串复制到一个字符数组char[] str中.
    char[] c = str.tochararray();
    system.out.println(c);
    for (int i = 0; i < c.length; i++) {
      system.out.print(c[i]);
    }
    system.out.println();
//   (4) 将字符串中每个单词的第一个字母变成大写, 输出到控制台。
      str=str.tolowercase();
      string[] tt=str.split(" ");
      system.out.println(tt.length);
      for(int i=0;i<tt.length;i++)
      {  
        //加个判断,长度大于0的
        if(tt[i].length()>0){
          system.out.print(string.valueof(tt[i].charat(0)).touppercase());
          system.out.print(tt[i].substring(1)+" ");
        }
      }
      system.out.println();
//   (5) 用两种方式实现该字符串的倒叙输出。(用stringbuffer和for循环方式分别实现)
      stringbuffer sb = new stringbuffer(str);
      system.out.println(sb.reverse().tostring());
      char[] c3 = str.tochararray();
      for (int i = c3.length-1; i >= 0 ; i--) {
        system.out.print(c3[i]);
      }
      system.out.println();
//   (6) 将本字符串转换成一个字符串数组,要求每个数组元素都是一个有意义的额英文单词,并输出到控制台
      string[] str5=str.split(" ");
      for (int i = 0; i < str5.length; i++) {
        system.out.print(str5[i]+", ");
      }
  }
}

输出结果:

字符串中字母s出现的次数:3 
test 
this is a test of java 
this is a test of java 
6 
this is a test of java 
avaj fo tset a si siht 
avaj fo tset a si siht 
this, is, a, test, of, java,

总结

以上就是本文关于java探索之string字符串的应用代码示例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:浅谈java编程tostring()方法重写的意义、等,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网