Finding substring in a given string by changing into char array - java

i am working on the following program. but its not giving me the correct output for string "nameiskhan" and substring as"name".
i know this might be a duplicate question but i couldn't find the desired answer in those questions.
import java.util.*;
import java.lang.String;
public class CheckingSubstring2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a String: ");
String string1 = input.next();
System.out.println("Please enter a second String: ");
String substring = input.next();
if (isSubstring(string1, substring)) {
System.out.println("The second string is a substring of the first.");
} else {
System.out.println("The second string is NOT a substring of the first.");
}
}
public static boolean isSubstring(String string1, String substring) {
char c[]=string1.toCharArray();
char d[]=substring.toCharArray();
boolean match = true;
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < d.length; j++) {
if (c[i] == d[j]) {
match = true;
} else {
match = false;
}
}
}
return match;
}
}

As you want to do it without contains, how about this?
What I do here is that going through the original string one pass and check if the substring can be found as consecutive characters in the main String.
public static boolean isSubstring(String string1, String substring) {
char c[]=string1.toCharArray();
char d[]=substring.toCharArray();
for (int i = 0; i < c.length; i++) {
if(c[i] == d[0]){
boolean match = false;
for(int j = 0; j < d.length; j++){
if(c[i+j] != d[j]){
match = false;
break;
} else{
match = true;
}
}
if(match) return true;
}
}
return false;
}

I would suggest becoming familiar with different debugging techniques. A very quick and easy one is a print statement. For example, you can print the values that you are comparing to make sure it looks reasonable. It will also give you an indication of how many times your loop is running. Stepping through the algorithm, the first two characters to be compared are c[0] = 'n' and d[0] = 'n'. That's good. The next two are c[0] = 'n' and d[1] = 'a'. That's not. Also, I assume you intend for the program to stop running if it finds a substring, but it doesn't appear that it would do so. Likewise, you might consider not comparing every element of the substring if a comparison has already been false.

Related

Check each position in the input entry and return the number of times a character occurs

I wrote the following code but I can't seem to convert the string to a char and then search the input entry string. My code is below. Any helpful tips would be greatly appreciated. I'm supposed to use a while loop but felt like for was easier to start with.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String inputEntry;
String inputCharacter;
int length;
int i;
int counter = 0;
System.out.println("Enter a string: ");
inputEntry = in.next();
System.out.println("Enter a letter: ");
inputCharacter = in.next();
length = inputCharacter.length();
if (length == 1) {
for(i = 0; i <= inputEntry.length(); i++){
char c = inputCharacter.charAt(0);
if (inputEntry.charAt(i) == c){
counter++;
}
}
}
else {
System.out.println("The input letter was not a single letter.");
}
}
}
It looks like the only problem in your code is that you are using <= instead of < within your loop. <= is incorrect because it passes string length as an index, but first character resides at charAt(0), and last character resides at charAt(inputEntry.length() - 1)
Replacing your loop declaration with the following will do the trick:
for(i = 0; i < inputEntry.length(); i++){
Then you also need to System.out.println(counter); after the for loop.

How to get rid of space at the end of output?

My code checks if a certain number of user inputted string have any repeated characters. For example, if I input the strings "google" "paper" and "water", the code returns "paper" and "water"; because "google" has two Os.
I have the code part down, but when printing, a space appears after the very last string that is output and I can't figure out how to get rid of it.
import java.util.Scanner;
import java.util.*;
class words{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number or words: ");
String[] words = new String[sc.nextInt()];
System.out.print("Enter the strings: ");
boolean truth = false;
for (int i = 0; i < words.length; i++) {
words[i] = sc.next();
}
for(int i=0;i<words.length;i++){
int j;
for(j=1;j<words[i].length();j++) {
if(words[i].charAt(j) == words[i].charAt(j-1)){
break;
}
}
if(j==words[i].length()){
truth = true;
System.out.print(words[i]+" ");
}
}
if(!truth){
System.out.println("NONE");
}
}
}
Functions Make Logic Readable
Move the logic to check for repeating characters into a function; I would take advantage of String.toCharArray() and the shorter array syntax. Like,
private static boolean repeatedChars(String s) {
if (s == null) {
return false;
}
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length - 1; i++) {
if (chars[i] == chars[i + 1]) {
return true;
}
}
return false;
}
Then, you can use a lambda to filter your words based on them not having repeated characters and collect with Collectors.joining(CharSequence) like
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number or words: ");
String[] words = new String[sc.nextInt()];
System.out.print("Enter the strings: ");
for (int i = 0; i < words.length; i++) {
words[i] = sc.next();
}
System.out.println(Arrays.stream(words).filter(s -> !repeatedChars(s))
.collect(Collectors.joining(" ")));
And, if you need to display the NONE message you might re-use the Predicate<String> like
Predicate<String> pred = s -> !repeatedChars(s);
if (Arrays.stream(words).anyMatch(pred)) {
System.out.println(Arrays.stream(words).filter(pred).collect(Collectors.joining(" ")));
} else {
System.out.println("NONE");
}
There is an easy workaround for your problem. Instead of printing every word immediately if it does not have any continuous repetition, add it to a String variable with space at the end so that each word is separated by a space. After you run through your loop, you check if your flag is false and print NONE if it is false. If it is true, however, print the result string where you added everything with a .trim() at the end.
for (int i = 0; i < words.length; i++) {
words[i] = sc.next();
}
String result = ""; /*This is the string that holds all the strings that you need to print.*/
for(int i=0;i<words.length;i++){
int j;
for(j=1;j<words[i].length();j++) {
if(words[i].charAt(j) == words[i].charAt(j-1)){
break;
}
}
if(j==words[i].length()){
truth = true;
result = result + (words[i]+" ");
}
}
if(!truth){
System.out.println("NONE");
}
else{
System.out.println(result.trim()); /*The trim function removes any redundant space in the beginning and the end of the string.*/
}
Of-course doing it this way will waste a lot of Heap Memory but I guess this is for a small learning project. However, do look into StringBuilder on how to use it to avoid creating a lot of memory in the Heap!

counting special characters in a user generated string

So I have this program that is supposed to to take any user generated string and display the amounts of white space, letters, numbers, and special characters. I do not want to duplicate a question. It seems to be a little more specific then talked about in other posts.
My error lies in the special characters. The specific error is return 0. I referenced stack overflow already in about every discussion they had on the matter. Which helped me form the special character method.
I have to keep the main method clear and call aforementioned methods
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
String userInput;
System.out.println("Please enter a string");
userInput = kbd.nextLine();
countletter(userInput);
countnumber(userInput);
countspecial(userInput);
countSpace(userInput);
}
public static void countletter(String userInput) {
int countletter = 0;
for (int i = 0; i < (userInput.length() - 1); i++) {
char location = userInput.charAt(i);
boolean x = Character.isLetter(location);
if (x) {
countletter++;
}
}
System.out.println("The number of Letters is: " + countletter);
}
public static void countnumber(String userInput) {
int countnumber = 0;
for (int i = 0; i < userInput.length() - 1; i++) {
char location = userInput.charAt(i);
boolean x = Character.isDigit(location);
if (x) {
countnumber++;
}
}
System.out.println("The number of digits is: " + countnumber);
}
public static void countSpace(String userInput) {
int countSpace = 0;
for (int i = 0; i < userInput.length() - 1; i++) {
char location = userInput.charAt(i);
boolean x = Character.isWhitespace(location);
if (x) {
countSpace++;
}
}
System.out.println("The number of white spaces is: " + countSpace);
}
public static void countspecial(String userInput) {
if (userInput == null || userInput.trim().isEmpty()) {
return 0;
}
int countSpecial = 0;
for (int i = 0; i < userInput.length(); i++) {
if (userInput.substring(i, 1).matches("[^A-Za-z0-9 ]")) {
countSpecial++;
}
}
System.out.println("The number of special chars is: " + countSpecial++);
}
}
My initial attempt at countSpecial:
public static void countspecial(String userInput) {
int countSpecial = 0;
for (int i = 0; i < (userInput.length() - 1); i++) {
if (userInput.substring(i, 1).matches("[^A-Za-z0-9]")) {
countSpecial++;
}
}
System.out.println("The number of special chars is: " + countSpecial++);
}
}
Where am I going wrong and why?
in your initial attemp you have problem with your substring
substring second parameter would be the index of your last character in the substring +1, and so you need to iterate until userInput.length() not userInput.length() -1.
And i dont know why would you increment the count after printing it , it actually does nothing but still makes no sense.
public static void countspecial(String userInput) {
if (userInput == null || userInput.trim().isEmpty()) {
return ;
}
int countSpecial = 0;
for (int i = 0; i < userInput.length(); i++) {
if (userInput.substring(i, i+1).matches("[^A-Za-z0-9]")) {
countSpecial++;
}
}
System.out.println("The number of special chars is: " + countSpecial);
}
A better way instead of subtring you could use "(userInput.charAt(i)+"").matches".
But a better solution would be counting all the digits and letters and subtract their sum form the total length of the string , this would give you the number of special characters as it is not recommended to use regex for simple requirement like this.
Look at the javadocs for substring.
Some languages that use a flavor of substring(int beginIndex, int length) where beginIndex is where you start the substring and length is how many characters are in the substring.
Java uses substring(int beginIndex, int endIndex) where beginIndex is where you start the substring and endIndex is the position of the ending character.
userInput.substring(i, 1);
Where i = 2 means you want to start the substring at index position 2 and end it at index position 1 and an exception is thrown.
If you're defining anything other than a letter, digit or whitespace character to be "special" then you should really test for it in the same way as the other tests so you don't miss anything because of different definitions of what constitutes a letter or digit. Character.isLetter() will return true for any Unicode letter, for example, not just ASCII A-Z or a-z. For consistency you should write:
char c = userInput.charAt(i);
if (!Character.isDigit(c) && !Character.isLetter(c) && !Character.isWhiteSpace(c)) {
countSpecial++;
}
But the problem in your original code is that the second parameter to String.substring() is the 'to' index, not a length. So if you were going to do with a regex it should be
if (userInput.substring(i, i+1).matches("[^A-Za-z0-9 ]")) {
countSpecial++;
}
Is this a practical example or are you asking for help doing an assignment? :-)
Even easier, don't loop. Just replace all non-special chars with nothing and count the length:
int countSpecial = userInput.replaceAll("[A-Za-z0-9\\s]", "").length();
You can apply this technique to all your character categories.

Check if charAt are the same (case sensitive)

Im have to write a method to check if a word is a palindrome. There is probably a easier way then I have it but this is just based off what I have learned so far. My method works except if there is a capital letters compared to a lowercase.
Edit: wasn't very clear. My method returns that a capital and lower case letter are the same. But I would like it to say they are different
public static void printPalindrome(Scanner kb) {
System.out.print("Type one or more words: ");
String s = kb.nextLine();
int count = 0;
for(int i = 0; i < s.length();i++) {
char a = s.charAt(i);
char b = s.charAt(s.length()-(i+1));
if (a==b) {
count ++;
} else {
count = count;
}
}
if (count == s.length()) {
System.out.print(s + " is a palindrome!");
} else {
System.out.print(s + " is not a palindrome.");
}
}
I'd recommend a slightly different approach, I'd reverse the string using StringBuilder#reverse and then compare the two strings using String#equalsIgnoreCase
String s = kb.nextLine();
StringBuilder sb = new StringBuilder(s).reverse();
if (s.equalsIgnoreCase(sb.toString())) {
...
} else {
...
}
You can solve your problem by converting the input String to upper case :
String s = kb.nextLine().toUpperCase();
Or if you wish to preserve the case of the original String, create a new String and test if it's a palindrome.
String s = kb.nextLine();
String u = s.toUpperCase();
int count = 0;
for(int i = 0; i < u.length();i++) {
char a = u.charAt(i);
char b = u.charAt(u.length()-(i+1));
if (a==b) {
count ++;
} else {
count = count;
}
}
i think you can do it with its ascii values
look this picture
then you shoul convert your char to ascii
char character = 'a';
int ascii = (int) character;
then compare the integers

How to search a sub string in string

I tried this code but this is not working for all strings.
import java.util.Scanner;
public class Substring {
public static void main(String[] args) {
String str;
String subStr;
int count=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the String : ");
str = in.nextLine();
System.out.println("Enter the Sub String : ");
subStr = in.nextLine();
for(int i =0 ; i <str.length(); i++)
{
if(str.charAt(i) == subStr.charAt(0))
{
for(int j=0 ; j<subStr.length();j++)
{
if( subStr.charAt(j) ==str.charAt(i+j))
count++;
else
{
count=0;
break;
}
}
}
}
if(count == subStr.length())
System.out.println("Sub String Matched !!");
else
System.out.println("String does not match !!");
}
}
What's wrong with this code ?
How to search a sub string in string
You don't need to loop over whole String. You can use string.indexOf(subString) to find the index of the substring in the string and it will return the index of the first occurrence of the substring. If you only want to ckeck whether String contains substring or not you can use string.contains(subString).
Try to decipher to the logic behind the code, so in plain english your code does the following:
LOGIC:
1)Enter a String via the Scanner and store it as str, do the same for the substring and store it as subStr.
2)Cycle through the each character of str via the for loop.
If the first character of the subStr is equal to any character with in str, then cycle through the characters of subStr. If the characters beyond this index are equal then increment the count variable each time the letters in each String are equal at the following indexes.
Else print String does not match.
3) If the number of similar characters in both Strings (denoted by the count variable) is equal to the length of the subString, then the subString is matched. Else no match.
ANSWER
So what went wrong?
I hope you notice on 2), The first bullet point you are only checking whether or not the first character of str is equal to the first character of subStr, if they are not equal you are then concluding that their is no match, which is false.
Consider the example:
str = "baloon"
subStr = "loon"
Your output would be: "String not matched"
This is because according to your code if 'b' != 'l' then theirs no match, which is false. That in essence is why your code does not work.
You could've just done the following:
if(str.contains(subStr)){
System.out.println("Sub-string matched");
}
Your code will only work if the substring is the end of the original string. This is because your code does not check that the entire substring was matched until it exits the first for loop. I moved the if (count == subStr.length() ) statement inside your first for loop and added a break if it finds the substring.
import java.util.Scanner;
public class Substring {
public static void main(String[] args) {
String str;
String subStr;
int count=0;
Scanner in = new Scanner(System.in);
System.out.println("Enter the String : ");
str = in.nextLine();
System.out.println("Enter the Sub String : ");
subStr = in.nextLine();
for(int i =0 ; i <str.length(); i++) {
if(str.charAt(i) == subStr.charAt(0)) {
for(int j=0 ; j<subStr.length();j++) {
if( subStr.charAt(j) ==str.charAt(i+j)) {
count++;
} else {
count=0;
break;
}
}
if(count == subStr.length()) {
System.out.println("Sub String Matched !!");
//int index = i;
break;
}
}
}
if(count == 0){
System.out.println("String does not match !!");
}
}
}
Note: If you then want the index at which the substring (first) occurred, you can set int index = i; before breaking the loop as shown in the commented line above.
Another note: don't tend to omit the {}s in if and else statements. While, technically, you don't need them for single statements, it can cause bugs if you need to edit code later...

Categories