In: Computer Science
So I need to make a java program that reverse or replace first or lastchar or remove char from user's string input.
length, concat, charAt, substring, and equals (or equalsIgnoreCase) thses are the string method that only I can use
for example
if user put asdf asdf and chose reverse
input should be fdsa fdsa
if user put asdf asdf and chose replace first a with b
input should be bsdf asdf
if user put asdf asdf and chose remove a and 2
input should be asdf sdf (remove 2nd 'a')
aaaaddd remove all 'a' = ddd
Since I cannot use replace or remove method I have no idea how to start this coding...
StringOperations.java
import java.util.ArrayList;
import java.util.Scanner;
public class StringOperations {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String inp = sc.nextLine().trim();
// reverse a string
System.out.println(inp + " in reverse order is: " +
reverse(inp));
// replace 1st and 2nd 'a' with 'b'
System.out.println("Replacing 1st a in " + inp + " with b gives: "
+ replace(inp, 'a', 'b', 1));
System.out.println("Replacing 2nd a in " + inp + " with b gives: "
+ replace(inp, 'a', 'b', 2));
// remove 1st and 2nd 'a'
System.out.println("Removing 1st a from " + inp + " gives: " +
remove(inp, 'a', 1));
System.out.println("Removing 2nd a from " + inp + " gives: " +
remove(inp, 'a', 2));
// remove all 'a' from a string
System.out.println("Removing all a's from " + inp + " gives: " +
removeAll(inp, 'a'));
System.out.println("Removing all a's from aaaaddd gives: " +
removeAll("aaaaddd", 'a'));
}
private static String reverse(String s)
{
String res = "";
for(int i = s.length() - 1; i >= 0; i--)
{
res += s.charAt(i);
}
return res;
}
private static String replace(String s, char target, char ch, int
pos)
{
String res = "";
int count = 0;
int index = -1;
ArrayList<Character> chars = new ArrayList<>();
for(int i = 0; i < s.length(); i++)
{
chars.add(s.charAt(i));
if(s.charAt(i) == target)
{
count++;
if(count == pos)
index = i;
}
}
if(count == 0 || pos < 0 || pos > count || index == -1)
res = "";
else
chars.set(index, ch);
for(Character c : chars)
{
res += c;
}
return res;
}
private static String remove(String s, char target, int pos)
{
String res = "";
int count = 0;
int index = -1;
ArrayList<Character> chars = new ArrayList<>();
for(int i = 0; i < s.length(); i++)
{
chars.add(s.charAt(i));
if(s.charAt(i) == target)
{
count++;
if(count == pos)
index = i;
}
}
if(count == 0 || pos < 0 || pos > count || index == -1)
res = "";
else
chars.set(index, '\0');
for(Character c : chars)
{
res += c;
}
return res;
}
private static String removeAll(String s, char target)
{
String res = "";
for(int i = 0; i < s.length(); i++)
{
if(s.charAt(i) != target)
res += s.charAt(i);
}
return res;
}
}
******************************************************************** SCREENSHOT *******************************************************