How to search a word in a string?
For example
String text = "Samsung Galaxy S Two";
If I use text.contains("???");
It will get any related alphabets even it is not a proper word such as "axy" from "Galaxy".
Any suggestion or solution?
List<String> tokens = new ArrayList<String>();
String text = "Samsung Galaxy S Two";
StringTokenizer st = new StringTokenizer(text);
//("---- Split by space ------");
while (st.hasMoreElements()) {
tokens.add(st.nextElement().toString());
}
String search = "axy";
for(int i=0;i<tokens.size();i++)
{
if(tokens.get(i).contains(search))
{
System.out.println("Word is "+tokens.get(i));
break;//=====> Remove Break if you want to continue searching all the words which contains `axy`
}
}
output====>Galaxy
For most simple usage, you can use a StringTokenizer
Look at this link.
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html
For using Regular expressions, Look at Patterns in android.
http://developer.android.com/reference/java/util/regex/Pattern.html
use indexOf:
int i= string.indexOf('1');
or substring:
String s=string.substring("koko",0,1);
Try this..
String string = "madam, i am Adam";
// Characters
// First occurrence of a c
int index = string.indexOf('a'); // 1
// Last occurrence
index = string.lastIndexOf('a'); // 14
// Not found
index = string.lastIndexOf('z'); // -1
// Substrings
// First occurrence
index = string.indexOf("dam"); // 2
// Last occurrence
index = string.lastIndexOf("dam"); // 13
// Not found
index = string.lastIndexOf("z"); // -1
I know this is an old question, but I am writing here so that the next person who needs help can be helped.
You can use matches.
String str = "Hello, this is a trial text";
str1 = str.toLowerCase();
if(str1.matches(".*trial.*")) //this will search for the word "trial" in str1
{
//Your Code
}
Related
I want to remove a part of string from one character, that is:
Source string:
manchester united (with nice players)
Target string:
manchester united
There are multiple ways to do it. If you have the string which you want to replace you can use the replace or replaceAll methods of the String class. If you are looking to replace a substring you can get the substring using the substring API.
For example
String str = "manchester united (with nice players)";
System.out.println(str.replace("(with nice players)", ""));
int index = str.indexOf("(");
System.out.println(str.substring(0, index));
To replace content within "()" you can use:
int startIndex = str.indexOf("(");
int endIndex = str.indexOf(")");
String replacement = "I AM JUST A REPLACEMENT";
String toBeReplaced = str.substring(startIndex + 1, endIndex);
System.out.println(str.replace(toBeReplaced, replacement));
String Replace
String s = "manchester united (with nice players)";
s = s.replace(" (with nice players)", "");
Edit:
By Index
s = s.substring(0, s.indexOf("(") - 1);
Use String.Replace():
http://www.daniweb.com/software-development/java/threads/73139
Example:
String original = "manchester united (with nice players)";
String newString = original.replace(" (with nice players)","");
originalString.replaceFirst("[(].*?[)]", "");
https://ideone.com/jsZhSC
replaceFirst() can be replaced by replaceAll()
Using StringBuilder, you can replace the following way.
StringBuilder str = new StringBuilder("manchester united (with nice players)");
int startIdx = str.indexOf("(");
int endIdx = str.indexOf(")");
str.replace(++startIdx, endIdx, "");
You should use the substring() method of String object.
Here is an example code:
Assumption: I am assuming here that you want to retrieve the string till the first parenthesis
String strTest = "manchester united(with nice players)";
/*Get the substring from the original string, with starting index 0, and ending index as position of th first parenthesis - 1 */
String strSub = strTest.subString(0,strTest.getIndex("(")-1);
I would at first split the original string into an array of String with a token " (" and the String at position 0 of the output array is what you would like to have.
String[] output = originalString.split(" (");
String result = output[0];
Using StringUtils from commons lang
A null source string will return null. An empty ("") source string will return the empty string. A null remove string will return the source string. An empty ("") remove string will return the source string.
String str = StringUtils.remove("Test remove", "remove");
System.out.println(str);
//result will be "Test"
If you just need to remove everything after the "(", try this. Does nothing if no parentheses.
StringUtils.substringBefore(str, "(");
If there may be content after the end parentheses, try this.
String toRemove = StringUtils.substringBetween(str, "(", ")");
String result = StringUtils.remove(str, "(" + toRemove + ")");
To remove end spaces, use str.trim()
Apache StringUtils functions are null-, empty-, and no match- safe
Kotlin Solution
If you are removing a specific string from the end, use removeSuffix (Documentation)
var text = "one(two"
text = text.removeSuffix("(two") // "one"
If the suffix does not exist in the string, it just returns the original
var text = "one(three"
text = text.removeSuffix("(two") // "one(three"
If you want to remove after a character, use
// Each results in "one"
text = text.replaceAfter("(", "").dropLast(1) // You should check char is present before `dropLast`
// or
text = text.removeRange(text.indexOf("("), text.length)
// or
text = text.replaceRange(text.indexOf("("), text.length, "")
You can also check out removePrefix, removeRange, removeSurrounding, and replaceAfterLast which are similar
The Full List is here: (Documentation)
// Java program to remove a substring from a string
public class RemoveSubString {
public static void main(String[] args) {
String master = "1,2,3,4,5";
String to_remove="3,";
String new_string = master.replace(to_remove, "");
// the above line replaces the t_remove string with blank string in master
System.out.println(master);
System.out.println(new_string);
}
}
You could use replace to fix your string. The following will return everything before a "(" and also strip all leading and trailing whitespace. If the string starts with a "(" it will just leave it as is.
str = "manchester united (with nice players)"
matched = str.match(/.*(?=\()/)
str.replace(matched[0].strip) if matched
someone can help me with code?
How to search word in String text, this word end "." or "," in java
I don't want search like this to find it
String word = "test.";
String wordSerch = "I trying to tasting the Artestem test.";
String word1 = "test,"; // here with ","
String word2 = "test."; // here with "."
String word3 = "test"; //here without
//after i make string array and etc...
if((wordSearch.equalsIgnoreCase(word1))||
(wordSearch.equalsIgnoreCase(word2))||
(wordSearh.equalsIgnoreCase(word3))) {
}
if (wordSearch.contains(gramer))
//it's not working because the word Artestem will contain test too, and I don't need it
You can use the matches(Regex) function with a String
String word = "test.";
boolean check = false;
if (word.matches("\w*[\.,\,]") {
check = true;
}
You can use regex for this
Matcher matcher = Pattern.compile("\\btest\\b").matcher(wordSearch);
if (matcher.find()) {
}
\\b\\b will match only a word. So "Artestem" will not match in this case.
matcher.find() will return true if there is a word test in your sentence and false otherwise.
String stringToSearch = "I trying to tasting the Artestem test. test,";
Pattern p1 = Pattern.compile("test[.,]");
Matcher m = p1.matcher(stringToSearch);
while (m.find())
{
System.out.println(m.group());
}
You can transform your String in an Array divided by words(with "split"), and search on that array , checking the last character of the words(charAt) with the character that you want to find.
String stringtoSearch = "This is a test.";
String whatIwantToFind = ",";
String[] words = stringtoSearch.split("\\s+");
for (String word : words) {
if (whatIwantToFind.equalsignorecas(word.charAt(word.length()-1);)) {
System.out.println("FIND");
}
}
What is a word? E.g.:
Is '5' a word?
Is '漢語' a word, or two words?
Is 'New York' a word, or two words?
Is 'Kraftfahrzeughaftpflichtversicherung' (meaning "automobile liability insurance") a word, or 3 words?
For some languages you can use Pattern.compile("[^\\p{Alnum}\u0301-]+") for split words. Use Pattern#split for this.
I think, you can find word by this pattern:
String notWord = "[^\\p{Alnum}\u0301-]{0,}";
Pattern.compile(notWord + "test" + notWord)`
See also: https://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
I have String of format something like this
String VIA = "1.NEW DELHI 2. Lucknow 3. Agra";
I want to insert a newline character before every digit occurring succeeded a dot so that it final string is like this
String VIA = "1.NEW DELHI " +"\n"+"2. Lucknow " +"\n"+"3. Agra";
How can I do it. I read Stringbuilder and String spilt, but now I am confused.
Something like:
StringBuilder builder = new StringBuilder();
String[] splits = VIA.split("\d+\.+");
for(String split : splits){
builder.append(split).append("\n");
}
String output = builder.toString().trim();
The safest way here to do that would be go in a for loop and check if the char is a isDigit() and then adding a '\n' before adding it to the return String. Please note, I am not sure if you want to put a '\n' before the first digit.
String temp = "";
for(int i=0; i<VIA.length(); i++) {
if(Character.isDigit(VIA.charAt(i)))
temp += "\n" + VIA.charAt(i);
} else {
temp += VIA.charAt(i);
}
}
VIA = temp;
//just use i=1 here of you want to skip the first charachter or better do a boolean check for first digit.
I am getting the names as String. How can I display in the following format: If it's single word, I need to display the first character alone. If it's two words, I need to display the first two characters of the word.
John : J
Peter: P
Mathew Rails : MR
Sergy Bein : SB
I cannot use an enum as I am not sure that the list would return the same values all the time. Though they said, it's never going to change.
String name = myString.split('');
topTitle = name[0].subString(0,1);
subTitle = name[1].subString(0,1);
String finalName = topTitle + finalName;
The above code fine, but its not working. I am not getting any exception either.
There are few mistakes in your attempted code.
String#split takes a String as regex.
Return value of String#split is an array of String.
so it should be:
String[] name = myString.split(" ");
or
String[] name = myString.split("\\s+);
You also need to check for # of elements in array first like this to avoid exception:
String topTitle, subTitle;
if (name.length == 2) {
topTitle = name[0].subString(0,1);
subTitle = name[1].subString(0,1);
}
else
topTitle = name.subString(0,1);
The String.split method split a string into an array of strings, based on your regular expression.
This should work:
String[] names = myString.split("\\s+");
String topTitle = names[0].subString(0,1);
String subTitle = names[1].subString(0,1);
String finalName = topTitle + finalName;
First: "name" should be an array.
String[] names = myString.split(" ");
Second: You should use an if function and the length variable to determine the length of a variable.
String initial = "";
if(names.length > 1){
initial = names[0].subString(0,1) + names[1].subString(0,1);
}else{
initial = names[0].subString(0,1);
}
Alternatively you could use a for loop
String initial = "";
for(int i = 0; i < names.length; i++){
initial += names[i].subString(0,1);
}
You were close..
String[] name = myString.split(" ");
String finalName = name[0].charAt(0)+""+(name.length==1?"":name[1].charAt(0));
(name.length==1?"":name[1].charAt(0)) is a ternary operator which would return empty string if length of name array is 1 else it would return 1st character
This will work for you
public static void getString(String str) throws IOException {
String[] strr=str.split(" ");
StringBuilder sb=new StringBuilder();
for(int i=0;i<strr.length;i++){
sb.append(strr[i].charAt(0));
}
System.out.println(sb);
}
I have strings of the form:
"abc" 1 2 1 13
"efgh" 2 5
Basically, a string in quotes followed by numbers separated by whitespace characters.
I need to extract the string and the numbers out of the line.
So for eg., for the first line, I'd want
abc to be stored in a String variable (i.e. without the quotations) and
an array of int to store [1,2,1,13].
I tried to create a pattern that'd do this, but I'm a little confused.
Pattern P = Pattern.compile("\A\".+\"(\s\d+)+");
Not sure how to proceed now. I realized that with this pattern I'd kinda be extracting the whole line out? Perhaps multiple patterns would help?
Pattern P1 = Pattern.compile("\A\".+\"");
Pattern P2 = Pattern.compile("(\s\d+)+");
Again, not very sure how to get the string and ints out of the line though. Any help is appreciated!
I would rather just split the string on space, rather than building complex regex, and use it with Pattern and Matcher class.
Something like this: -
String str = "\"abc\" 1 2 1 13 ";
String[] arrr = str.split("\\s");
System.out.println(Arrays.toString(arrr));
OUTPUT: -
["abc", 1, 2, 1, 13]
Shows your intent much clearer, that what you want to do.
Then, you can get the string and integer parts from your string array. You would need to do a Integer.parseInt() on integer elements.
If your string may contain spaces in it, then in that case, you would need a Regex. Better one would be the one in #m.buettner's answer
Use capturing groups to get both parts in one go, then split the numbers at spaces.
Pattern pattern = Pattern.compile("\"([^\"]*)\"\\s*([\\d\\s]*)");
Matcher m = pattern .matcher(input);
while (m.find()) {
String str = m.group(1);
String[] numbers = m.group(2).split("\\s");
// process both of them
}
Each set of parentheses in the regex will later correspond to one group (counting opening parentheses from left to right, starting at 1).
Please try this it will separate both String and int also
String s = "\"abc\" 1 2 1 13 ";
s = s.replace("\"", "");
String sarray[] = s.split(" ");
int i[] = new int[10];
String si[] = new String[10];
int siflag = 0;
int iflag = 0;
for (String st : sarray) {
try {
int ii = Integer.parseInt(st)
i[iflag++] = ii;
} catch (NumberFormatException e) {
si[siflag++] = st;
}
}
StringTokenizer st = new StringTokenizer(str,"\" ");
String token = null;
String strComponent = null;
int num[] = new int[10]; // can change length dynamically by using ArrayList
int i = 0;
int numTemp = -1;
while(st.hasMoreTokens()){
token = st.nextToken();
try{
numTemp = Integer.parseInt(token);
num[i++] = numTemp ;
}catch(NumberFormatException nfe){
strComponent = token.toString();
}