Click here to Skip to main content
15,896,393 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have tried this function to delete a single char from string many times but it stucks .. .can anyone please help

What I have tried:

Java
public String deleteChar (String s1, char c1)
{
    int i,j;
    char s2[]=s1.toCharArray();
    for(i=0;i<s2.length;i++)
    {
        if(s2[i]==c1)
        {
            j=i;

            while(j<s2.length-1)
            {
                s2[j]=s2[j+1] ;
            }
        s2[j+1]=' ' ;
        }
    }
    return String.valueOf(s2);
}


and this main method

Java
public static void main(String args[])     {       
    System.out.println("Enter the input String:");         
    Scanner scan = new Scanner(System.in);         
    Str str2 = new Str(scan.nextLine());         
    System.out.println("Enter the character to be deleted :");         
    char c1 = scan.next().charAt(0) ;         
    str2.input = str2.deleteChar(str2.input, c1);         
    System.out.println("The output String is :" + str2.input);
}
Posted
Updated 14-Apr-17 9:57am
v2

Does it even compile? In the line
Str str2 = new Str(scan.nextLine());
Str is not a valid type.

Also, in your while block where you are moving the text, you forgot to increment the value of your index variable j.
 
Share this answer
 
Quote:
it stucks

Define the kind of "stuck".
Assuming that 'stuck' means that you don't get expected result, the best is to run the code in debugger and see what it does.

Java
str2.input = str2.deleteChar(str2.input, c1);

As far as I understand, 'deleteChar' is not a string method.

When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute, it is an incredible learning tool.

Debugger - Wikipedia, the free encyclopedia[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900