In: Computer Science
JAVA coding language:
Consider the method getAllCharAsString:
public statis String getAllCharAsString(String inputStr, char target) {
}
The method accepts a String parameter, inputStr, and a char parameter, target. It returns the result string consisting of all the characters in inputStr which match the target character (matching is case sensitive, for example, 'c' does not match "C"). If the characters match, the character is appended to the result String. After all the characters in inputStr have been compared, the method returns the result String. The method returns the empty String if there were no matches. Assume the inputStr is a String with length >= 0.
Example 1:
String str = "Open the pod bay doors Hal.";
String resStr = getAllCharsAsString(str, 'o');
resStr would be the String, "ooo".
Example 2:
String str = "Open the pod bay doors Hal.";
String resStr = getAllCharsAsString(str, 'z');
resStr would be the empty String, " ".
Write the getAllCharAsString method body in the box below.
CODE:
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new
Scanner(System.in);
//taking inputs from user.
System.out.print("Enter string :
");
String inputStr =
scan.nextLine();
System.out.print("Enter Character :
");
char target =
scan.next().charAt(0);
//calling function to get result
string.
String resStr =
getAllCharAsString(inputStr,target);
System.out.println("The result
string is : "+resStr);
}
public static String getAllCharAsString(String
inputStr, char target)
{
String result ="";//Result
string
//converting target to string
String tar =
Character.toString(target);
//loop through the string.
for (int
i=0;i<inputStr.length();i++)
{
//condition to
check the target in string.
if(inputStr.charAt(i) == target)
{
result += tar;//adding the chars matched to
string.
}
}
return result;//returning the
resultant string.
}
}
CODE ATTACHMENTS:
OUTPUT:
Please do comment for any queries.
Please like it.
Thank you.