[英]How I can split a word without a delimiter and perform operations over the split string in Java 8?
This is the code that I have created.这是我创建的代码。 I want to Split a word - "UUDDUUDD".我想拆分一个词 - “UUDDUUDD”。 I want to perform an operation on every character that I receive from this word.我想对从这个词收到的每个字符执行操作。 So, I tried using the below code.I'm getting the error as所以,我尝试使用下面的代码。我得到的错误是
error: incompatible types: String cannot be converted to String[]错误:不兼容的类型:字符串无法转换为字符串 []
If I'm not using an array ie String[] newPath and just write as String newPath , I would not be able to perform iteration operation over the string.如果我不使用数组,即String[] newPath并且只写为String newPath ,我将无法对字符串执行迭代操作。 Can you help me to know how can I iterate over the new array?你能帮我知道如何迭代新数组吗?
for (String[] newPath: path.split(""))
for (char[] newPath: path.split("")
{
if (newPath[i]=="U")
{
count++;
}
else
{
count= count-1;
}
}
You have to use toCharArray()
that's convert String
into char[]
.您必须使用toCharArray()
将String
转换为char[]
。 Remeber for char
use 'U'
not "U"
.记住char
使用'U'
而不是"U"
。 Here is a correct code:这是一个正确的代码:
public static void main(String[] args) {
String path = "UUDDUUDD";
int count = 0;
for (char newPath: path.toCharArray()) {
if (newPath == 'U') {
count++;
} else {
count--;
}
}
}
Split function returns a String array.拆分 function 返回一个字符串数组。 In your for loop you should iterate over these values by using a simple String, so newPath is a String, not a String array.在你的 for 循环中,你应该使用一个简单的字符串来迭代这些值,所以 newPath 是一个字符串,而不是一个字符串数组。 If you want just count 'U' chars in String:如果您只想计算字符串中的“U”字符:
public static void main(String[] args) {
String path = "UUDDUUDD";
long count = path.chars()
.filter(ch -> ch == 'U')
.count();
System.out.println("number of Us: " + count);
}
Increment count if char is 'U' and decrement otherwise:如果 char 是 'U' 则增加计数,否则减少:
public static void main(String[] args) {
String path = "UUDDUUDD";
long countResult = path.chars()
.reduce(0, (i, j) -> j == 'U' ? i + 1 : i - 1);
System.out.println(countResult);
}
The return type of String.split() is String[]. String.split() 的返回类型是 String[]。
So if we are iterating over the result of String.split() we use a String:因此,如果我们迭代 String.split() 的结果,我们将使用一个字符串:
class Test {
public static void main(String[] args) {
for (String c : "ABCD".split("")) {
System.out.println(c);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.