Check for Duplicate Strings in an Array
- Program, which checks for duplicate string in an array of strings.
Program
import
java.util.Scanner;
public class
DuplicateString {
private static
Scanner sc;
public static void
main(String[] args) {
int
limit,flag=0;
String str;
sc=new
Scanner(System.in);
System.out.println("Enter
the limit for the Array of strings:");
limit=sc.nextInt();
String[] string=new
String[limit+1];
System.out.println("Enter
the strings in the Array:");
for(int
i=0;i<limit;i++) {
str=sc.next();
string[i]=str;
}
for(int
i=0;i<limit;i++) {
for(int
j=i;j<limit;j++) {
if(string[i].equals(string[j+1]))
{
flag++;
if(flag==1)
{
System.out.println("Dupication
exists for strings:");
}
System.out.println(string[i]);
break;
}
}
}
if(flag==0)
{
System.out.println("No
Duplications exist");
}
}
}
Output
Enter
the limit for the Array of strings:
5
Enter
the strings in the Array:
Sachin
Ponting
Kapil
Waugh
Sachin
Dupication
exists for strings:
Sachin
- Program to insert and delete a string from an array of strings. Write a program that displays a menu to the user
a) Insert String
b) Delete Strings
c)
Exit
Program
import
java.io.IOException;
import
java.util.ArrayList;
import
java.util.Scanner;
public class InsertDeleteString {
private static
Scanner sc;
public static void
main(String[] args) throws IOException {
int
choice;
char
proceed;
String str;
sc=new
Scanner(System.in);
ArrayList<String>
ar=new ArrayList<String>();
do {
System.out.println("Enter
your choice:\n1.Insert\n2.Delete\n3.Exit");
choice=sc.nextInt();
switch(choice)
{
case 1: System.out.println("Enter
the string to be inserted:");
str=sc.next();
ar.add(str);
System.out.println("The
contents of the Array:\n"+ar);
break;
case 2: System.out.println("Enter
the string to be deleted:");
str=sc.next();
ar.remove(str);
System.out.println("The
contents of the Array:\n"+ar);
break;
case 3: System.exit(0);
break;
default: System.out.println("Invalid
choice");
break;
}
System.out.println("Do
you want to continue:(y/n)?");
proceed=(char)
System.in.read();
}while(proceed=='Y'||proceed=='y');
}
}
Output
Enter
your choice:
1.Insert 2.Delete 3.Exit
1
Enter
the string to be inserted:
Apple
The
contents of the Array:
[Apple]
Do
you want to continue:(y/n)?
y
Enter
your choice:
1.Insert 2.Delete 3.Exit
1
Enter
the string to be inserted:
Orange
The
contents of the Array:
[Apple,
Orange]
Do
you want to continue:(y/n)?
y
Enter
your choice:
1.Insert 2.Delete 3.Exit
2
Enter
the string to be deleted:
Apple
The
contents of the Array:
[Orange]
Do
you want to continue:(y/n)?
n
No comments:
Post a Comment