Search for a sub-string
- Function, which checks whether one string is a sub-string of another string.
Program
import
java.util.Scanner;
public class
SubString {
private static
Scanner sc;
public static void
main(String[] args) {
String str,substr;
sc=new
Scanner(System.in);
System.out.println("Enter
the string:");
str=sc.nextLine();
System.out.println("Enter
the substring:");
substr=sc.nextLine();
if(str.contains(substr))
{
System.out.println("\""+substr+"\"
is a substring of \""+str+"\"");
}
else {
System.out.println("\""+substr+"\"
is not a substring of \""+str+"\"");
}
}
}
Output
Enter
the string:
sub-string
Enter
the substring:
string
"string"
is a substring of "sub-string"
- Program that accepts a sentence and returns the sentence with all the extra spaces trimmed off. (In a sentence, words need to be separated by only one space; if any two words are separated by more than one space, remove extra spaces)
Program
import
java.util.Scanner;
public class
RemoveExtraSpace {
private static
Scanner sc;
public static void
main(String[] args) {
int
len=0;
sc=new
Scanner(System.in);
System.out.println("Enter
the String:");
String str=sc.nextLine();
for(int
i=1;i<str.length();i++) {
if(str.charAt(i)=='
') {
len++;
}
}
for(int
j=0;j<len;j++) {
str=str.replaceAll(" ", "
");
}
System.out.println("The
new string is:\n"+str);
}
}
Output
Enter
the String:
Trim all
extra spaces.
The
new string is:
Trim
all extra spaces.
No comments:
Post a Comment