Java中统计字符个数以及反序非相同字符的方法详解
程序员文章站
2023-12-14 15:07:46
复制代码 代码如下:import java.util.arraylist;import java.util.list;public class test2 { /...
复制代码 代码如下:
import java.util.arraylist;
import java.util.list;
public class test2 {
/**
* @param args
*/
public static void main(string[] args) {
string src = "a b c d e b c";
//替换掉空格
src = src.replaceall(" ", "") ;
system.out.println("去除空格后字符串:" + src) ;
list<character> list = new arraylist<character>() ;
int[] bb = new int[256];
char[] cs = src.tochararray();
//倒序
int mid = cs.length / 2 ;
int idx = cs.length -1 ;
for (int i = 0; i < mid ; i++){
char tmp = cs[i] ;
cs[i] = cs[idx] ;
cs[idx] = tmp ;
idx-- ;
}
//统计,并且过滤相同的
for (char c : cs) {
if (bb[c] <1) {
list.add(c) ;
}
bb[c] = bb[c] + 1;
}
system.out.println();
for (int i = 0; i < list.size(); i++){
system.out.print(list.get(i)) ;
}
system.out.println() ;
for (int i = 0; i < list.size(); i++){
char c = list.get(i) ;
system.out.println(c + " " + bb[c] + "次") ;
}
}
}
string a = "abcd,efg";
string b = ")(*&^%$#@![]{},.//;:'? <>";
要求是判断string a 里有没有哪个字符在string b里出现 ,效率越高越好
* 查找某些字符是否在另一个字符串里出现
复制代码 代码如下:
*
* @author java人(java2000.net)
*/
public class test {
/**
* @param args
*/
public static void main(string[] args) {
string a = "abcd,efg";
string b = ")(*&^%$#@![]{},.///;:'? <>";
byte[] bb = new byte[256];
char[] cs = b.tochararray();
for (char c : cs) {
bb[c] = 1;
}
cs = a.tochararray();
for (char c : cs) {
if (bb[c] == 1) {
system.out.println(c);
}
}
}
}