[英]How to loop over all characters in a String array
I am working a Hash Table project. 我正在做一个哈希表项目。 So I have an array which will hold the Strings. 所以我有一个将容纳字符串的数组。 ArrayList<String> buckets = new ArrayList<>();
I want to create a method hash
but I am stuck on how to make that method takes in a String and loops over the individual characters in that string and sums their number values all together, and then return the integer sum. 我想创建一个方法hash
但我仍然坚持如何使该方法接受一个String并循环遍历该字符串中的各个字符,然后将它们的数字值求和,然后返回整数和。
The method hash
will use for the test below: 方法hash
将用于以下测试:
@Test
public void testToString() {
HashTable h= new HashTable(10);
org.junit.Assert.assertEquals( "Empty hash output" ,
"(0)\t\n"
+"(1)\t\n"
+"(2)\t\n"
+"(3)\t\n"
+"(4)\t\n"
+"(5)\t\n"
+"(6)\t\n"
+"(7)\t\n"
+"(8)\t\n"
+"(9)\t\n"
, h+""/*.toString()*/
);
}
@Test
public void hashFunction() {
HashTable h= new HashTable(10);
org.junit.Assert.assertEquals( "hash function test" ,
4
, h.hash("abc") % h.size()
);
org.junit.Assert.assertEquals( "hash function test backwards string" ,
4
, h.hash("cba") % h.size()
);
Thank you in advances! 预先感谢您!
There are several ways of doing it - for example, you can use charAt(i)
and a for
loop: 有几种方法可以执行此操作-例如,可以使用charAt(i)
和for
循环:
int sum = 0;
for (int i = 0 ; i != s.length() ; i++) {
sum += s.charAt(i);
}
You could also convert the string to an array of characters, and use it in a for (char ch : s.toCharArray())
statement, but it would result in an additional memory allocation for the array of characters. 您也可以将字符串转换为字符数组,并在for (char ch : s.toCharArray())
语句中使用它,但这将导致为字符数组分配额外的内存。
Note 1: you should watch out for numeric overflow. 注意1:您应注意数字溢出。
Note 2: Consider using a different method for computing hash values. 注意2:考虑使用其他方法来计算哈希值。 Adding up character codes would work, but strings with reordered characters would have identical hash codes. 添加字符代码将可以工作,但是具有重新排序的字符的字符串将具有相同的哈希码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.