黑马程序员技术交流社区
标题:
在字符串中得到某字符每一次出现的位置
[打印本页]
作者:
老衲玩IT
时间:
2013-8-27 08:53
标题:
在字符串中得到某字符每一次出现的位置
package com.itheima;
import static com.itheima.MyCharArray.*;
/**
* 在一个类中编写一个方法,这个方法搜索一个字符数组中是否存在某个字符,
* 如果存在,则返回这个字符在字符数组中第一次出现的位置(序号从0开始计算),
* 否则,返回-1。要搜索的字符数组和字符都以参数形式传递传递给该方法。
* @author Administrator
*
*/
public class Test {
public static void main(String[] args) {
char[] array="public static void main(String[] args)".toCharArray();
System.out.println(MyCharArray.indexOfChars(array, 'v'));
System.out.println(MyCharArray.indexOfChars(array, 'e'));
System.out.println(MyCharArray.indexOfChars(array, 'j'));
System.out.println(MyCharArray.indexOfChars(array, 'K'));
System.out.println(MyCharArray.indexOfChars(array, 'l'));
System.out.println(indexOfChars(null, 'e'));
}
}
class MyCharArray{
/* public static int indexOfChars(String str,char ch){
if (str==null) {
throw new IllegalArgumentException();
}
return indexOfChars(str.toCharArray(), ch);
}*/
public static int indexOfChars(char[] array,char ch){
if (array==null) {
throw new IllegalArgumentException();
}
for (int i = 0; i < array.length; i++) {
if (ch==array[i]) {
return i;
}
}
return -1;
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2