任何人都可以帮助我解决这个问题:
编写一个程序,该程序创建一个字符串中出现的字符的一致性(即哪些字符出现在字符串中的哪个位置)。从命令行读取字符串。 运行程序:
java Concordance Hello World
{d = [9],o = [4,6],r = [7],W = [5],H = [0],l = [2,3,8],e = [1 ]}
我试试这段代码:
package q4;
public class Q4 {
public static void main(String[] args) {
// Scanner input = new Scanner(System.in);
// String string = input.nextLine();
// indexOfChar(string);
indexOfChar("hello");
}
@SuppressWarnings("empty-statement")
public static void indexOfChar(String string) {
int counter;
counter = 0;
String letter;
int[] letterCounter = new int[26];
letter = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < string.length(); i++) {
counter = 0;
letterCounter[letter.indexOf(string.charAt(i))]++;
}
counter = 0;
for (int i = 0; i < letterCounter.length; i++) {
if (letterCounter[i] != 0) {
counter++;
}
}
String s = null;
for (int i = 0; i < string.length(); i++) {
// char ch=name.charAt(i);
if (letterCounter[letter.indexOf(string.charAt(i))] != 0) {
System.out.print(string.charAt(i) + "=[");
}
for (int j = i; j < string.length(); j++) {
if (string.charAt(i) == string.charAt(j)) {
System.out.print(j + ",");
}
}
System.out.println("]");
}
//System.out.println(counter);
}
}
答案 0 :(得分:3)
您可以使用Map将每个角色映射到其出现的位置。您可以在列表上使用集合,因为每个位置在字符串中都是唯一的。
class Test{
private static Map<Character, Set<Integer>> characterConcordance(final String input) {
Map<Character, Set<Integer>> concordance = new HashMap<Character, Set<Integer>>();
for (int i = 0; i < input.length(); i++) {
char charAt = input.charAt(i);
if (charAt == ' ') {
continue; // ignore spaces
}
Set<Integer> set= concordance.get(charAt);
if (set == null) {
set= new HashSet<Integer>();
}
set.add(i + 1); // use i for 0-indexed, or (i+1) for 1-indexed positions
concordance.put(charAt, set);
}
return concordance;
}
public static void main(final String[] args) {
System.out.println(Test.characterConcordance("Java is cool!!"));
//prints {v=[3], !=[13, 14], s=[7], c=[9], a=[2, 4], o=[10, 11], l=[12], J=[1], i=[6]}
}
}
答案 1 :(得分:-2)
我解决了这个问题:
package q4;
import java.util.*;
public class Q4{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String str = input.nextLine();
char []data=str.toCharArray();
Set s = new HashSet();
for(int i=0; i<data.length; i++){
s.add(data[i]);
}
Object[] s1 = s.toArray();
System.out.print("{ ");
for(int i=0; i<s.size(); i++){
System.out.print(s.toArray()[i]+"=");
Collection t = new ArrayList();
char c=(Character) s1[i];
for(int j=0;j<data.length; j++){
if(c==data[j]){
t.add(j);
}
}
System.out.print(t+ ", ");
}
System.out.print("}");
}
}