[英]How to insert a char before each char in a string, but not before 'space' in Java?
This is what I got.这就是我得到的。 It works for now, but if I type, for example, "I like bananas", I get 'pIp ppipkpep pbpapnpapnpaps', while I'm aiming to get 'pI pLpipkpe pbpapnpapnpaps.它现在有效,但如果我输入,例如,“我喜欢香蕉”,我会得到 'pIp ppipkpep pbpapnpapnpaps',而我的目标是得到 'pI pLpipkpe pbpapnpapnpaps。
Every solution I tried came down to using an 'if statement', trying to check if the character at said position in the original 'encText'is equal to ' ', and if so, making it equal to ' ' as well in the newText array before checking if the position required an 'p' or the char from the original array.. However, everytime I tried that, I'd get an array out of bounds exception.我尝试的每个解决方案都归结为使用“if 语句”,试图检查原始“encText”中所述 position 处的字符是否等于“”,如果是,则使其在 newText 中也等于“”在检查 position 是否需要原始数组中的 'p' 或 char 之前的数组。但是,每次我尝试这样做时,我都会得到一个数组越界异常。
static void pEncrypt() {
System.out.println("Adding P");
Scanner in = new Scanner(System.in);
String encText = in.nextLine();
int k = encText.length();
char[] charsEncText = encText.toCharArray();
char[] newText = new char[2*k];
int j = 1;
for (int i = 0; i < (k*2); i++) {
if (i%2 == 0) {
newText[i] = 'p';
} else {
newText[i] = charsEncText[i-j];
j++;
}
}
System.out.println(newText);
}
A simpler solution is to use replaceAll
with a positive lookahead .一个更简单的解决方案是使用带有正向预测的replaceAll
。
String str = "I like bananas";
String res = str.replaceAll("(?=[^ ])", "p");
System.out.println(res); // "pI plpipkpe pbpapnpapnpaps"
Assuming one does not need a char[]
, I would just concatenate to a String
.假设不需要char[]
,我只会连接到String
。 Something like:就像是:
public static String pEncrypt(String org)
{
String ret = "";
for (int i = 0; i < org.length(); ++i) {
char ch = org.charAt(i);
if (ch != ' ') {
ret += "p" + ch;
}
else {
ret += ' ';
}
}
return ret;
}
Also, to make things a bit easier, it is generally a good idea to separate the I/O (ie, the Scanner
and the println
) from the processing.此外,为了使事情更容易一些,将 I/O(即Scanner
和println
)与处理分开通常是一个好主意。 That way, one can write test cases rather than attempting to keep inputting the information.这样一来,人们就可以编写测试用例,而不是试图继续输入信息。
Sample Output:样品 Output:
helloworld ==> phpeplplpopwpoprplpd
I like bananas ==> pI plpipkpe pbpapnpapnpaps
You can try this way.你可以试试这个方法。
static void pEncrypt() {
System.out.println("Adding P");
Scanner in = new Scanner(System.in);
String encText = in.nextLine();
int k = encText.length();
char[] charsEncText = encText.toCharArray();
char[] newText = new char[2*k];
int j=0;
for(int i=0;i<k;i++)
{
if(charsEncText[i]==' ')
{
newText[j]=charsEncText[i];
j++;
}
else{
newText[j]='p';
newText[j+1]=charsEncText[i];
j=j+2;
}
}
System.out.println(newText);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.