[英]How do i remove extra spaces while printing two string variables in java
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int T = scan.nextInt();
for ( int i=0; i<T ; i++)
{
String str = scan.next();
int even =0 , odd =0, len = str.length();
String str1=null, str2=null;
char [] str_even = new char[50];
char [] str_odd = new char[50];
for ( int j=0 ; j<len ; j ++)
{
if ( j %2 ==0)
{
str_even[even] = str.charAt(j);
even++ ;
str1 = String.valueOf(str_even);
}
if (j%2!=0)
{
str_odd[odd] = str.charAt(j);
odd++ ;
str2 = String.valueOf(str_odd);
}
}
String output = str1+str2 ;
System.out.print(output);
}
scan.close();
}
if inputstring is如果输入字符串是
Hacker
Rank
Expected output:预期 output:
Hce akr
Rn ak
My Output:我的 Output:
Hce akr
Rn
a
It looks like you are converting the entire fixed length char[]
into a String
, but you only want the a portion of it.看起来您正在将整个固定长度的
char[]
转换为String
,但您只想要它的一部分。 Fortunately there is a three-arg overload of String.valueOf
that combines a substring
.幸运的是,有一个
String.valueOf
的三参数重载,它结合了substring
。
str1 = String.valueOf(str_even, 0, even);
It lookes like you will also need to add a separator space back into the output.看起来您还需要在 output 中添加一个分隔空间。
(Not that there aren't other general issues with the code.) (并不是说代码没有其他一般性问题。)
if you want to remove spaces there are many options.如果你想删除空格,有很多选择。
// Remove spaces , tabs and returns
System.out.println(text.replaceAll("\\s",""));
// Remove spaces in the beginning and at the end
System.out.println(text.trim());
Hope it helped.希望它有所帮助。
First, your arrays are of the wrong size.首先,您的 arrays 尺寸错误。 Use this:
用这个:
char [] str_even = new char[(len+1)/2];
char [] str_odd = new char[len/2];
second, you don't need to create str1
and str2
at each iteration.其次,您不需要在每次迭代时创建
str1
和str2
。 Create them after the loop.在循环之后创建它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.