This question already has answers here:
How do I concatenate two strings in Java?
(23 answers)
Closed 5 years ago.
Below is my code I'm expecting the output as "afbgchde" and not "abcdefgh" but ending up with out of index error, Hope there is a better way to get this..Please help..!!
String str1 = "abcde";
//char[] a = str1.toCharArray();
//System.out.println(a);
String str2 = "fgh";
char[] b = str2.toCharArray();
//System.out.println(b);
int i,j=0;
try
{
for(i=0;i<str1.length();i++)
{
char c = str1.charAt(i);
System.out.print(c);
if(j==i)
{
char d = str2.charAt(j);
System.out.print(d);
j++;
}
}
}
catch(Exception e)
{
System.out.println(e);
}
Simple:
char d = str2.charAt(j);
System.out.print(d);
j++;
You are accessing chars in your second string; but you never bother to check if j is still < str2.length().
Meaning: your for-loop for i contains that check; and prevents going beyond the length of str ... but then you forget to do that on your other string! So your merge only works when str and str2 happen to have the same size.
So a solution would more look like:
StringBuilder builder = new StringBuilder();
int j = 0;
for (int i=0; i < str.length(); i++) {
builder.append(str.charAt(i));
if (j < str2.length()) {
builder.append(str2.charAt(j));
j++;
}
}
// if str2 has more chars than str
if (j < str2.length()) {
// append ALL chars starting from index j
builder.append(str2.substring(j));
}
String merged = builder.toString();
Complete Code for your combiner.
public class StringCombiner {
public static void main(String[] args){
System.out.println(combine("Hello", "World"));
System.out.println(combine("He", "World"));
System.out.println(combine("Hello", "Wo"));
}
public static String combine(String str1, String str2){
StringBuilder output = new StringBuilder();
int i =0;
for(; i< str1.length(); ++i){
output.append(str1.charAt(i));
if(i < str2.length()){
output.append(str2.charAt(i));
}
}
if(i < str2.length()){
for(; i<str2.length(); ++i){
output.append(str2.charAt(i));
}
}
return output.toString();
}
}
Output:
HWeolrllod
HWeorld
HWeollo
Hope this helps.
Okay. Lets try this
String str1 = "abcde";
String str2 = "fgh";
int bigLength = str1.length()>str2.length()?str1.length():str2.length();
for(int i = 0; i<bigLength; i++){
if(i<str1.length())
System.out.print(str1.charAt(i))
if(i<str2.length())
System.out.print(str2.charAt(i))
}
Hope this will work for you.
just use StringBuilder class man
if you want to change a value of a String object
String class is an object that is unchangeable or can't be change when it is initialized
StringBuilder class is the best solution for any String that you want to have a change while the application is running
e.g. add a String or change value of a String or even shorten a String
that is the power of StringBuilder class
`
Related
What's the error in the following code? I am not able to identify it shows the index 0 out of bounds exception.
public class stringBuilders{
public static void main(String[] args)
{
StringBuilder str = new StringBuilder("Shubham");
StringBuilder str2= new StringBuilder();
int j=0;
for(int i = str.length()-1; i>=0 ; i--)
{
str2.setCharAt(j++,str.charAt(i));
}
System.out.print(str2);
}
}
As you are already iterating from end to start you can just append the characters to the fresh and empty string builder. setChar() is only intended to replace existing characters.
public class StringBuilders {
public static void main(String[] args) {
String str = "Shubham";
StringBuilder str2 = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
str2.append(str.charAt(i));
}
System.out.println(str2.toString());
}
}
gives
$ java StringBuilders.java
mahbuhS
You haven't declared a value to the str2 string.
The for loop is trying to find a character at index j=0 in str2 to set value i of str2, which it cannot find.
Hence the error.
For this to work, you need declare a value of str2 to a length >= str1. i.e., if str1 = "0123456", str2 should be at least 0123456 or more.
Instead of using StringBuilder to set the char, you can use String to just append to it.
String str1 = new String("Shubham");
String str2 = new String();
int iter = str1.length() -1;
for(int i=iter; i>=0; i--) {
str2 += str1.charAt(i);
}
System.out.println(str2)
I am comparing two strings and try to print out comman latters but i could not avoid to repeat a latter more than once.
here is my code
public static String getCommonCharacters ( final String a, final String b){
String result="";
for(int i = 0; i < a.length(); i++){
for(int j = 0; j < b.length(); j++)
if(a.charAt(i)==b.charAt(j)){
result +=a.charAt(i);
}
} return result;
the problem is when a = "baac" and b =" fdeabac " then i get out = "aabaac" instead of "abc" or "bca" etc
change the if condition to:
if (a.charAt(i) == b.charAt(j) &&
!result.contains(String.valueOf(a.charAt(i)))) { ... }
Thus, you only perform the statement:
result +=a.charAt(i);
if the accumulating string doesn't already contain the character.
Working code with minor modification to yours:
public class StringCompare {
public static String getCommonCharacters(final String a, final String b) {
String result = "";
for (int i = 0; i < a.length(); i++) {
for (int j = 0; j < b.length(); j++)
if (a.charAt(i) == b.charAt(j)) {
result += a.charAt(i);
}
}
return result;
}
public static void main(String[] args) {
System.out.println(getCommonCharacters("baac", "fdeabac ").replaceAll(
"(.)\\1{1,}", "$1")); // You could use regular expressions for
// that. Removing repeated characters.
}
}
Output:
bac
Pattern explanation:
"(.)\1{1,}" means any character (added to group 1) followed by itself at least once
"$1" references contents of group 1
More about Regular Expressions Oracle Docs
Hier is another solution: create two new HashSet for each String which we change to charArray, then add them to hashSet with For loops,
retainAll() method provide used to remove it's elements from a list that are not contained in the specified collection.#Java Doc by Oracle
Last For-Loop used to concatenate char as a strings.
String str ="";
Set<Character> s1 = new HashSet<Character>();
Set<Character> s2 = new HashSet<Character>();
for(char c:a.toCharArray()) s1.add(c);
for(char c:b.toCharArray()) s2.add(c);
s1.retainAll(s2);
for(char s:s1) str +=s;
return str;
This question already has answers here:
Replace a character at a specific index in a string?
(9 answers)
Closed 6 years ago.
I am trying to create a method that will consume two Strings. It will Compare String 1 with String 2 and will replace all unfound chars with '_'. For example if String 1 = "Hello"; String 2 = "eo" then the method will return String 1 as "_e__o" Here is my code:
static String getRevealedChars (String s1, String s2)
{
for (int i = 0; i < s1.length(); i++)
{
for (int c = 0; c < s2.length(); c++)
{
if (s1.charAt(i) == s2.charAt(c))
{
break;
}
else
{
// this is where I get my Error
s1.charAt(i) = '_';
}
}
}
}
However, when I run this code I get a "unexpected type" error at s1.charAt(i) = '_';. I'm really new to java, thanks in advance.
Replace datatype of s1 and s2 from String to StringBuilder, then use setCharAt() instead of charAt() as follows:
StringBuilder s1 = new StringBuilder("hello");
StringBuilder s2 = new StringBuilder("eo");
static String getRevealedChars (StringBuilder s1, StringBuilder s2)
{
for (int i = 0; i < s1.length(); i++)
{
for (int c = 0; c < s2.length(); c++)
{
if (s1.charAt(i) == s2.charAt(c))
{
break;
}
else
{
// this is where I corrected Error
s1.setCharAt(i, '_');
}
}
}
}
Hope this helps. Good luck.
I want to create a static method Static String displayArray (int [] array) that takes an integer array as parameter, uses a loop to create and return a new String that represents the contents of the array surrounded by braces and separated by commas.
For example,
int [] myArray = { 12,9,10,25};
String str = displayArray(myArray);
System.out.println (str); // should display {12,9,10,25}
My solution:
public static String displayArray (int [] array) {
for (int i=0; i< array.length; i++) {
System.out.println(array[i]);
}
return null;
}
But it gives output as follows:
12
9
10
25
null
You need to build a String object to return. Right now you are returning null, which is literally nothing.
I'd suggest using a StringBuilder, it's a little faster than concatenating Strings directly. So before your loop you'll want to define a StringBuilder object and add the opening brace:
StringBuilder returnString = new StringBuilder();
returnString.append("{");
Then within your loop, you can concatenate each number:
returnString.append(Integer.toString(array[i]);
After that you'll want to make a check to see if you have the last element, if not, append a comma.
Finally append the closing brace, and instead of return null use:
return returnString.toString();
You might need this:
public static String displayArray(int[] array) {
StringBuilder builder = new StringBuilder("{");
for (int i = 0; i < array.length; i++) {
builder.append((array[i])).append(",");
}
return builder.substring(0, builder.length() - 1).concat("}");
}
Something like this:
public static String displayArray (int [] array) {
StringBuilder sb = new StringBuilder();
for (int i=0; i< array.length; i++) {
sb.append(array[i]);
if(i!=array.length-1)
sb.append(",");
}
return "{"+sb.toString()+"}";
}
Yes, exactly it is giving you the right output.
To get your desired output you can modify your display array function as follow:
public static String displayArray (int [] array) {
String str = "";
for (int i=0; i< array.length; i++) {
str += array[i]+",";
}
returns str;
}
public static String displayArray( int[] array )
{
return "{" + Arrays.toString( array ).replace("[", "").replace("]", "") + "}";
}
Going off of #BorisTheSpider idea and because I find this easier than Stringbuilder, here is your method to return the string { val1, val2, val3 }.
Basically, print out your braces manually and replace the brackets with "".
Do this instead:
public static String displayArray (int [] array) {
StringBuilder sb = new StringBuilder();
for (int i=0; i< array.length; i++) {
sb.append(array[i]+",");
}
String result=sb.toString()+",";
result=result.replace(",,","");
return "{"+result+"}";
}
None of the answers display the output like you wanted it.
public static String displayArray (int [] array) {
StringBuilder sb = new StringBuilder();
sb.append("{");
for (int i=0; i< array.length; i++) {
sb.append(array[i]);
if(i != array.length-1)
sb.append(",");
}
sb.append("}");
return sb.toString();
}
I am new to java programming. I want to print a string with alternate characters in UpperCase.
String x=jTextField1.getText();
x=x.toLowerCase();
int y=x.length();
for(int i=1;i<=y;i++)
{}
I don't know how to proceed further. I want to do this question with the help of looping and continue function.
Help would be appreciated. Thanks.
#Test
public void alternateUppercase(){
String testString = "This is a !!!!! test - of the emergency? broadcast System.";
char[] arr = testString.toLowerCase().toCharArray();
boolean makeUppercase = true;
for (int i=0; i<arr.length; i++) {
if(makeUppercase && Character.isLetter(arr[i])) {
arr[i] = Character.toUpperCase(arr[i]);
makeUppercase = false;
} else if (!makeUppercase && Character.isLetter(arr[i])) {
makeUppercase = true;
}
}
String convertedString = String.valueOf(arr);
System.out.println(convertedString);
}
First, java indexes start at 0 (not 1). I think you are asking for something as simple as alternating calls to Character.toLowerCase(char) and Character.toUpperCase(char) on the result of modulo (remainder of division) 2.
String x = jTextField1.getText();
for (int i = 0, len = x.length(); i < len; i++) {
char ch = x.charAt(i);
if (i % 2 == 0) {
System.out.print(Character.toLowerCase(ch));
} else {
System.out.print(Character.toUpperCase(ch));
}
}
System.out.println();
Strings start at index 0 and finish at index x.length()-1
To look up a String by index you can use String.charAt(i)
To convert a character to upper case you can do Character.toUpperCase(ch);
I suggest you build a StringBuilder from these characters which you can toString() when you are done.
you can make it using the 65 distnace of lower case and upper case ABCabc from the unicode table like:
String str = "abbfFDdshFSDjdFDSsfsSdoi".toLowerCase();
char c;
boolean state = false;
String newStr = "";
for (int i=0; i<str.length(); i++){
c = str.charAt(o);
if (state){
newStr += c;
}
else {
newStr += c + 65;
}
state = !state;
}
I'm sure there is a slicker way to do this, but this will work for a 2 minute-answer:
public String homeWork(){
String x = "Hello World";
StringBuilder sb = new StringBuilder();
for(int i=0;i<=x.length();i++){
char c = x.charAt(i);
if(i%2==0){
sb.append(String.valueOf(c).toUpperCase());
} else {
sb.append(String.valueOf(c).toLowerCase());
}
}
return sb.toString();
}
To explain i%2==0, if the remainder of i divided by 2 is equal to zero (even numbered) return true
public class PrintingStringInAlternativeCase {
public static void main(String s[])
{
String testString = "TESTSTRING";
String output = "";
for (int i = 0; i < testString.length(); i++) {
if(i%2 == 0)
{
output += Character.toUpperCase(testString.toCharArray()[i]);
}else
{
output += Character.toLowerCase(testString.toCharArray()[i]);
}
}
System.out.println("Newly generated string is as follow: "+ output);
}
}
Using as much of your code as I could, here's what I got. First I made a string called build that will help you build your resulting string. Also, I changed the index to go from [0,size-1] not [1,size]. Using modulo devision of 2 helps with the "every other" bit.
String build =""
String x=jTextField1.getText();
x=x.toLowerCase();
int y=x.length();
for(int i=0;i<y;i++)
{
if(i%2==0){
build+=Character.toUpperCase(x.charAt(i));
else{
build+=x.charAt(i);
}
}
x=build; //not necessary, you could just use build.
Happy oding! Leave a comment if you have any questions.
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Stirng");
String str=sc.nextLine();
for(int i=0;i<str.length();i++)
{
if(i%2==0)
{
System.out.print(Character.toLowerCase(str.charAt(i)));
}
else
{
System.out.print(Character.toUpperCase(str.charAt(i)));
}
}
sc.close();
}
Java 8 Solution:
static String getMixedCase(String str) {
char[] chars = str.toCharArray();
return IntStream.range(0, str.length())
.mapToObj(i -> String.valueOf(i % 2 == 1 ? chars[i] : Character.toUpperCase(chars[i])))
.collect(Collectors.joining());
}
public class ClassC {
public static void main(String[] args) {
String str = "Hello";
StringBuffer strNew = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
if (i % 2 == 0) {
strNew.append(Character.toLowerCase(str.charAt(i)));
} else {
strNew.append(Character.toUpperCase(str.charAt(i)));
}
}
System.out.println(strNew);
}
}