I would like to find same word in two string.
startpoint = newresult.indexOf('\'');
endpoint = newresult.lastIndexOf('\'');
variables = newresult.substring(startpoint, endpoint);
variables = variables.replace("\r\n", ",");
variables = variables.replaceAll("'", "");`
String variables:
cons,john,$,alex,manag;
String second:
ins_manages(john,cons)
As it is seen, both strings they have john and cons and I want to check if both have same char sequences or not but I don't know how it can be checked? Is there any way to check it directly?
Solution:
String [] newvar;
newvar = variables.split(",");
After that, I used a for loop and matched them one by one.
BR
Split both the strings and compare the individual words using foreach as shown below:
String first = "hello world today";
String second = "Yet another hello worldly day today";
//split the second string into words
List<String> wordsOfSecond = Arrays.asList(second.split(" "));
//split and compare each word of the first string
for (String word : first.split(" ")) {
if(wordsOfSecond.contains(word))
System.out.println(word);
}
Your requirements are a little ambiguous. You're asking to find the same singular word in two strings, then your sample asks for finding two words in the same strings.
For verifying that one single word is in two strings, you can just do:
public boolean bothStringsContainWord(String s1, String s2, String word) {
return s1.contains(word) && s2.contians(word);
}
You can put that in a loop if you need to do it over multiple words. Again, your requirements are a little fuzzy though; if you straighten them up a more efficient solution probably exists.
Related
This program is to return the readable string for the given morse code.
class MorseCode{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String morseCode = scanner.nextLine();
System.out.println(getMorse(morseCode));
}
private static String getMorse(String morseCode){
StringBuilder res = new StringBuilder();
String characters = new String(morseCode);
String[] charactersArray = characters.split(" "); /*this method isn't
working for
splitting what
should I do*/
for(String charac : charactersArray)
res.append(get(charac)); /*this will return a string for the
corresponding string and it will
appended*/
return res.toString();
}
Can you people suggest a way to split up the string with multiple whitespaces. And can you give me some example for some other split operations.
Could you please share here the example of source string and the result?
Sharing this will help to understand the root cause.
By the way this code just works fine
String source = "a b c d";
String[] result = source.split(" ");
for (String s : result) {
System.out.println(s);
}
The code above prints out:
a
b
c
d
First, that method will only work if you have a specific number of spaces that you want to split by. You must also make sure that the argument on the split method is equal to the number of spaces you want to split by.
If, however, you want to split by any number of spaces, a smart way to do that would be trimming the string first (that removes all trailing whitespace), and then splitting by a single space:
charactersArray = characters.trim().split(" ");
Also, I don't understand the point of creating the characters string. Strings are immutable so there's nothing wrong with doing String characters = morseCode. Even then, I don't see the point of the new string. Why not just name your parameter characters and be done with it?
Say i have a simple sentence as below.
For example, this is what have:
A simple sentence consists of only one clause. A compound sentence
consists of two or more independent clauses. A complex sentence has at
least one independent clause plus at least one dependent clause. A set
of words with no independent clause may be an incomplete sentence,
also called a sentence fragment.
I want only first 10 words in the sentence above.
I'm trying to produce the following string:
A simple sentence consists of only one clause. A compound
I tried this:
bigString.split(" " ,10).toString()
But it returns the same bigString wrapped with [] array.
Thanks in advance.
Assume bigString : String equals your text. First thing you want to do is split the string in single words.
String[] words = bigString.split(" ");
How many words do you like to extract?
int n = 10;
Put words together
String newString = "";
for (int i = 0; i < n; i++) { newString = newString + " " + words[i];}
System.out.println(newString);
Hope this is what you needed.
If you want to know more about regular expressions (i.e. to tell java where to split), see here: How to split a string in Java
If you use the split-Method with a limiter (yours is 10) it won't just give you the first 10 parts and stop but give you the first 9 parts and the 10th place of the array contains the rest of the input String. ToString concatenates all Strings from the array resulting in the whole input String. What you can do to achieve what you initially wanted is:
String[] myArray = bigString.split(" " ,11);
myArray[10] = ""; //setting the rest to an empty String
myArray.toString(); //This should give you now what you wanted but surrouned with array so just cut that off iterating the array instead of toString or something.
This will help you
String[] strings = Arrays.stream(bigstring.split(" "))
.limit(10)
.toArray(String[]::new);
Here is exactly what you want:
String[] result = new String[10];
// regex \s matches a whitespace character: [ \t\n\x0B\f\r]
String[] raw = bigString.split("\\s", 11);
// the last entry of raw array is the whole sentence, need to be trimmed.
System.arraycopy(raw, 0, result , 0, 10);
System.out.println(Arrays.toString(result));
I know it's a wierd to ask a question like this. But i've got no options. The problem is
I've come across a requirement where i happens to add a condition where, If there is an input as a string, I should be able to allow all the strings which only contains one word. So if there are many words I should reject.
How to add such check when I don't have specificity on such string.
If the words are separated by some kind of white space, you could use a simple regular expression for this:
Pattern wordPattern = Pattern.compile("\\w+");
Matcher wordMatcher = wordPattern.matcher(inputString);
if (!wordMatcher.matches()) {
// discard user input
}
This will match all word characters ([a-zA-Z_0-9]). If your definition of "word" is different, the regex will need to be adapted.
So many ways you can achieve it,
One of the simplest is..
String str = "abc def";
String [] array = str.trim().split(" ");
if(array.lenght==1){
// allow if lenght = 1, or a word....
}else{
// don't allow if lenght !=1 , or not a word..., dosomething else, or skip
}
You can split the string on a regular expression that represents a sequence of white spaces and then see how many parts you get. Here's a function to do it:
public static boolean is_word(String s) {
return (s.length() > 0 && s.split("\\s+").length == 1);
}
System.out.println(is_word("word"));
System.out.println(is_word("two words"));
System.out.println(is_word("word\tabc\txyz"));
System.out.println(is_word(""));
Output:
true
false
false
false
The length check on the input string is required if you want to say that an empty string is not a word, which would seem reasonable.
Suppose I have a string:
String advise = "eat healthy food";
In the string I only know the keyword “healthy”. I don’t know what has before the word nor what has after the word. I just only know the middle word. So how can I get the before (“eat”) and after (“food”) keyword of “healthy”?
Note: Here the middle word’s size is always specfic but the other two word’s size is always different. Here “eat” and “food” have been used as an example only. These two words may be anything anytime.
I need to get these two words into two different strings, not in the same string.
Just split the string:
advise.split("healthy");
The first value in the array will be "eat", the second will be "food".
Here is a more general purpose solution that will handle more complex strings.
public static void main (String[] args)
{
String keyword = "healthy";
String advise = "I want to eat healthy food today";
Pattern p = Pattern.compile("([\\s]?+[\\w]+[\\s]+)" + keyword + "([\\s]+[\\w]+[\\s]?+)");
Matcher m = p.matcher(advise);
if (m.find())
{
String before = m.group(1).trim();
String after = m.group(2).trim();
System.out.println(before);
System.out.println(after);
}
else
{
System.out.println("The keyword was not found.");
}
}
Outputs:
eat
food
I think you can use split and get all the words separately as you wanted.
String advise = "eat healthy food";
String[] words = advise.split("healthy");
List<String> word = Arrays.asList(words);
word.forEach(w-> System.out.println(w.trim()));
so i have to write a java code to :
Input a name
Format name in title case
Input second name
Format name in title case
Display them in alphabet order
i know that The Java Character class has the methods isLowerCase(), isUpperCase, toLowerCase() and toUpperCase(), which you can use in reviewing a string, character by character. If the first character is lowercase, convert it to uppercase, and for each succeeding character, if the character is uppercase, convert it to lowercase.
the question is how i check each letter ?
what kind of variables and strings should it be contained ?
can you please help?
You should use StringBuilder, whenver dealing with String manipulation.. This way, you end up creating lesser number of objects..
StringBuilder s1 = new StringBuilder("rohit");
StringBuilder s2 = new StringBuilder("jain");
s1.replace(0, s1.length(), s1.toString().toLowerCase());
s2.replace(0, s2.length(), s2.toString().toLowerCase());
s1.setCharAt(0, Character.toTitleCase(s1.charAt(0)));
s2.setCharAt(0, Character.toTitleCase(s2.charAt(0)));
if (s1.toString().compareTo(s2.toString()) >= 0) {
System.out.println(s2 + " " + s1);
} else {
System.out.println(s1 + " " + s2);
}
You can convert the first character to uppercase, and then lowercase the remainder of the string:
String name = "jOhN";
name = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
System.out.println(name); // John
For traversing Strings using only the String class, iterate through each character in a string.
String s = "tester";
int size = s.length(); // length() is the number of characters in the string
for( int i = 0; i < size; i++) {
// s.charAt(i) gets the character at the ith code point.
}
This question answers how to "change" a String - you can't. The StringBuilder class provides convenient methods for editing characters at specific indices though.
It looks like you want to make sure all names are properly capitalized, e.g.: "martin ye" -> "Martin Ye" , in which case you'll want to traverse the String input to make sure the first character of the String and characters after a space are capitalized.
For alphabetizing a List, I suggest storing all inputted names to an ArrayList or some other Collections object, creating a Comparator that implements Comparator, and passing that to Collections.sort()... see this question on Comparable vs Comparator.
This should fix it
List<String> nameList = new ArrayList<String>();
nameList.add(titleCase("john smith"));
nameList.add(titleCase("tom cruise"));
nameList.add(titleCase("johnsmith"));
Collections.sort(nameList);
for (String name : nameList) {
System.out.println("name=" + name);
}
public static String titleCase(String realName) {
String space = " ";
String[] names = realName.split(space);
StringBuilder b = new StringBuilder();
for (String name : names) {
if (name == null || name.isEmpty()) {
b.append(space);
continue;
}
b.append(name.substring(0, 1).toUpperCase())
.append(name.substring(1).toLowerCase())
.append(space);
}
return b.toString();
}
String has a method toCharArray that returns a newly allocated char[] of its characters. Remember that while Strings are immutable, elements of arrays can be reassigned.
Similarly, String has a constructor that takes a char[] representing the characters of the newly created String.
So combining these, you have one way to get from a String to a char[], modify the char[], and back to a new String.
This can be achieved in any number of ways, most of which will come down to the details of the requirements.
But the basic premise is the same. String is immutable (it's contents can not be changed), so you need away to extract the characters of the String, convert the first character to upper case and reconstitute a new String from the char array.
As has already been pointed out, this is relative simple.
The other thing you might need to do, is handle multiple names (first, last) in a single pass. Again, this is relatively simple. The difficult part is when you might need to split a string on multiple conditions, then you'll need to resort to a regular expression.
Here's a very simple example.
String name = "this is a test";
String[] parts = name.split(" ");
StringBuilder sb = new StringBuilder(64);
for (String part : parts) {
char[] chars = part.toLowerCase().toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
sb.append(new String(chars)).append(" ");
}
name = sb.toString().trim();
System.out.println(name);