Java 忽略字符串数组中的特定元素
我正在编写一个程序,它忽略了字符串中“/”和“/”符号之间的所有内容,就像真实场景中的IDE一样。我将字符串拆分为行并存储在数组中,然后使用while循环从当前行中的单个字符构建单词,忽略符号,但是我的输出不太正确 下面是我试图实现的一个例子Java 忽略字符串数组中的特定元素,java,Java,我正在编写一个程序,它忽略了字符串中“/”和“/”符号之间的所有内容,就像真实场景中的IDE一样。我将字符串拆分为行并存储在数组中,然后使用while循环从当前行中的单个字符构建单词,忽略符号,但是我的输出不太正确 下面是我试图实现的一个例子 Phrase: The quick brown /* fox jumped over the */ lazy dog. Desired output: The quick brown lazy dog. 基本上删除了注释之间的所有内容 这是我目前的尝试
Phrase: The quick brown /* fox jumped over the */ lazy dog.
Desired output: The quick brown lazy dog.
基本上删除了注释之间的所有内容
这是我目前的尝试
public class Testing6 {
public static void main(String[] args) {
String riddle = "The Quick \n" +
" brown /* fox \n" +
" jumped over \n" +
" the */ lazy \n" +
" dog \n";
String[] lines = riddle.split("\\r?\\n");
for (String line : lines) {
int n = line.length();
int index = 0;
String word = "";
while (index < n) {
char ch = line.charAt(index);
word = word + ch;
if (ch == ' ' ) //if ch is empty, word is complete, print word.
{
System.out.println(word);
word = "";
}
if (ch == '/' || ch == '*') { // checking for symbols
index++;
if (ch == '*' || ch == '/')
{
index++;
break; // breaking if symbols match
}
}
index++;
}
}
}
}
提前感谢您的反馈。我正在修改您的答案,以便按照您的期望显示该行。这里没有对代码进行真正的增强 以下是代码中的问题:
println
,它在新行中打印每个字符串String riddle = "The Quick \n" +
" brown /* fox \n" +
" jumped over \n" +
" the */ lazy \n" +
" dog \n";
String[] lines = riddle.split("\\r?\\n");
String word = "";
for (String line : lines) {
int n = line.length();
for (int index = 0; index < n; index++) {
char ch = line.charAt(index);
if (ch == ' ') { // if ch is empty, word is complete, print word.
if (!word.isEmpty()) { // do not log empty word
word = word + ch;
System.out.print(word);
word = "";
}
continue;
}
if (ch == '/' || ch == '*') { // checking for symbols
index++;
if (ch == '*' || ch == '/') {
index++;
break; // breaking if symbols match
}
}
word = word + ch; // only non-empty chars are added here
}
}
请注意,根据您的输入,最后一个单词可能包含额外的空格。但我想你可以从这里开始。你的问题是什么?如果你只是想检查你的代码,去应聘者需要修改他的代码。这不是真正的代码审查。
String riddle = "The Quick \n" +
" brown /* fox \n" +
" jumped over \n" +
" the */ lazy \n" +
" dog \n";
String[] lines = riddle.split("\\r?\\n");
String word = "";
for (String line : lines) {
int n = line.length();
for (int index = 0; index < n; index++) {
char ch = line.charAt(index);
if (ch == ' ') { // if ch is empty, word is complete, print word.
if (!word.isEmpty()) { // do not log empty word
word = word + ch;
System.out.print(word);
word = "";
}
continue;
}
if (ch == '/' || ch == '*') { // checking for symbols
index++;
if (ch == '*' || ch == '/') {
index++;
break; // breaking if symbols match
}
}
word = word + ch; // only non-empty chars are added here
}
}
The Quick brown jumped over the dog