黑马程序员技术交流社区

标题: 在字符串中得到某字符每一次出现的位置 [打印本页]

作者: 老衲玩IT    时间: 2013-8-27 08:53
标题: 在字符串中得到某字符每一次出现的位置
  1. package com.itheima;
  2. import static com.itheima.MyCharArray.*;
  3. /**
  4. * 在一个类中编写一个方法,这个方法搜索一个字符数组中是否存在某个字符,
  5. * 如果存在,则返回这个字符在字符数组中第一次出现的位置(序号从0开始计算),
  6. * 否则,返回-1。要搜索的字符数组和字符都以参数形式传递传递给该方法。
  7. *  @author Administrator
  8. *
  9. */
  10. public class Test {

  11.         public static void main(String[] args) {
  12.                 char[] array="public static void main(String[] args)".toCharArray();
  13.                 System.out.println(MyCharArray.indexOfChars(array, 'v'));
  14.                 System.out.println(MyCharArray.indexOfChars(array, 'e'));
  15.                 System.out.println(MyCharArray.indexOfChars(array, 'j'));
  16.                 System.out.println(MyCharArray.indexOfChars(array, 'K'));
  17.                 System.out.println(MyCharArray.indexOfChars(array, 'l'));
  18.                 System.out.println(indexOfChars(null, 'e'));
  19.         }

  20. }
  21. class MyCharArray{
  22. /*        public static int indexOfChars(String str,char ch){
  23.                 if (str==null) {
  24.                         throw new IllegalArgumentException();
  25.                 }
  26.                 return indexOfChars(str.toCharArray(), ch);
  27.         }*/
  28.         public static int indexOfChars(char[] array,char ch){
  29.                 if (array==null) {
  30.                         throw new IllegalArgumentException();
  31.                 }
  32.                 for (int i = 0; i < array.length; i++) {
  33.                         if (ch==array[i]) {
  34.                                 return i;
  35.                         }
  36.                 }
  37.                 return -1;
  38.         }
  39. }
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2