题目:
1. 给定一个字符串,判断该字符串中是否包含某个子串.如果包含,求出子串的所有出现位置.
如:"abcbcbabcb34bcbd"中,"bcb"子串的出现位置为: 1,7,12.字符串和子串均由用户输入
2.给定一个长度,随机产生一个该长度的字符串,由大写,小写字母以及数字组成
Java中随机数的生成:
java.util.Random r = new java.util.Random();
int a = r.nextInt(100): a 0-99的随机数
3.给定一个由数字组成的字符串,如:"1239586838923173478943890234092",统计
出每个数字出现的次数
答案如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
package
Chp10;
import
java.util.HashMap;
import
java.util.Map;
import
java.util.Random;
import
java.util.Scanner;
import
java.util.Set;
public
class
TestString2
{
public
static
void
Method_One()
{
Scanner s =
new
Scanner(System.in);
System.out.println(
"请输入一个父串"
);
String str = s.next();
System.out.println(
"请输入一个子串"
);
String str1 = s.next();
int
stat =
0
;
while
(
true
)
{
int
i = str.indexOf(str1,stat);
if
(i==-
1
)
{
break
;
}
System.out.println(i);
stat = i+str1.length();
}
}
public
static
void
Method_Two()
{
System.out.println(
"请输入一个长度"
);
Scanner s =
new
Scanner(System.in);
int
n = s.nextInt();
char
[] cs =
new
char
[n];
Random random =
new
Random();
for
(
int
i =
0
; i < n; i++)
{
int
a = random.nextInt(
62
);
if
(a>=
0
&& a<=
25
)
{
a+=
65
;
}
else
if
(a>
25
&& a<=
51
)
{
// 97 - 26 = 71
a+=
71
;
}
else
{
// 52-48 = 4
a-=
4
;
}
cs[i] = (
char
)a;
}
System.out.println(cs);
}
public
static
void
Method_Three()
{
Scanner scanner =
new
Scanner(System.in);
String string = scanner.next();
int
[] c =
new
int
[
10
];
for
(
int
i =
0
; i < string.length(); i++)
{
char
c1 = string.charAt(i);
//48-57
int
a = c1-
48
;
// 类型转换
c[a]++;
}
for
(
int
i =
0
; i < c.length; i++)
{
System.out.println(i+
" 出现的次数: "
+c[i]);
}
System.out.println(
"=========方法二=========="
);
String s =
"12548954231351486214894562"
;
char
[] ch = s.toCharArray();
Map<Character, Integer> map =
new
HashMap<Character, Integer>();
Set<Character> set = map.keySet();
for
(
int
i =
0
; i < ch.length; i++)
{
if
(set.contains(ch[i]))
// 判断map中已经有的char值
{
map.put(ch[i], map.get(ch[i])+
1
);
}
else
{
map.put(ch[i],
1
);
// 第一次放入map中
}
}
Set<Character> set2 = map.keySet();
for
(Character character : set2)
{
System.out.println(character+
"=========="
+map.get(character));
}
}
public
static
void
main(String[] args)
{
System.out.println(
"第一题如下:"
);
Method_One();
System.out.println(
"第二题如下:"
);
Method_Two();
System.out.println(
"第三题如下:"
);
Method_Three();
}
}
|