zoukankan      html  css  js  c++  java
  • 28. string类中方法练习

    1. 自己写trim方法

    public class Demo3 {
        public static void main(String[] args) {
            System.out.println(myTrim("     123     "));
        }
        //需求:去除字符串两边空格的函数
        public static String myTrim(String str){
            int start = 0;
            int end = str.length()-1;
            //去掉前面的空格
            for (int i = 0; i < str.length()-1; i++) {
                char ch = str.charAt(start);
                if(ch == ' '){
                    start++; 
                }else{
                    break;
                }
            }
            //去掉后面的空格
            
            for (int i = end; i >0; i--) {
                char ch = str.charAt(i);
                if(ch == ' '){
                    end--;
                }else{
                    break;
                }
            }
            //截取字符串(因为不包含最后一位数,所以加1)
            return str.substring(start,end+1);
            
            
        }
    }

    2.获取上传文件名  "D:\20120512\day12\Demo1.java"

    public class Demo4 {
        public static void main(String[] args) {
            System.out.println(getFilename("D:\20120512\day12\Demo1.java"));
        }
        
        //需求:获取上传文件名  "D:\20120512\day12\Demo1.java"
        public static String getFilename(String path){
            
            //根据获取最后一个的索引+1
            int start = path.lastIndexOf('\')+1;
            
            return path.substring(start); 
        }
    }

    3.将字符串对象中存储的字符反序

    public class Demo5 {
        public static void main(String[] args) {
            System.out.println(reaverseString("hello"));
        }
        
        //需求:将字符串对象中存储的字符反序
        public static String reaverseString(String str){
            char[] ch = str.toCharArray();
            for (int start = 0,end = ch.length-1; start < end; start++,end--) {
                char temp = ch[start];
                ch[start] = ch[end];
                ch[end] = temp;
            }
            return new String(ch);
        }
    }

    4. 求一个子串在整串中出现的次数

    public class Demo6 {
        public static void main(String[] args) {
            System.out.println(getCount("abcabcjgejgabc","abc"));
        }
        //求一个子串在整串中出现的次数
        public static int getCount( String src , String tag ){ 
              // 0. 定义索引变量和统计个数的变量
              int index = 0;
              int count = 0;       
              // 1. 写循环判断
              while ( ( index = src.indexOf(tag) ) != -1 ){
                  src = src.substring( index + tag.length() );   // index 4 + 4 = 8
                  count++;
              }
              return count;
        }
    }
  • 相关阅读:
    逻辑回归与最大熵模型
    提升方法-AdaBoost
    Python中的类属性、实例属性与类方法、静态方法
    mysqldump详解
    12.python 模块使用,面向对象介绍
    11 python 内置函数
    10.函数的变量与返回值
    9. 函数的定义和参数,默认参数
    linux下iptables详解
    把linux下的yum源更换为阿里云的国内源
  • 原文地址:https://www.cnblogs.com/zjdbk/p/8910980.html
Copyright © 2011-2022 走看看