I have a string .. I need to search for some particular texts inside this string if it is present total numbers need to be returned.
I know how to return a character of particular place
String string = "Hi How are you";
b = string.contains("H") ;
But I need to get multiple characters for example..I need to search for 'A' and 'S' inside a string and I need number of times it is coming.
how I will write the code for that.I know how to search in a particular place and search for a particular character. But how for more than i character and return its total number.
String string = "Hai How are you!";
char aChar = anotherPalindrome.charAt(9);
I know it will reeturn 9th place character.
String string = "Niagara. O roar again!";
String roar = string.substring(5, 7);
I know it will return 'How'
You have to use regular expressions. Android provides the Pattern class to this kind of things.
You can do like this here three characters AJS can be searched.. if you need to search its small characters give like 'AaJaSs'..
String string;
Pattern pattern = Pattern.compile("([AJS])"); //case insensitive
Matcher matcher = pattern.matcher(String);
int count = 0;
while (matcher.find()) count++;
Try looping with help of the indexOf() method.
Example:
String exampleString = "Hai How are you!";
String searchedString = "H";
int index = exampleString.indexOf(searchedString , 0);
int counter = 0;
while(index != -1) {
counter++;
int index = exampleString.indexOf(searchedString , index);
}
System.out.println("The character " + searchedString + " occurs " + counter + " times.");
You can make a method to count the frequency of the character in the string :
public static int count(char character){
return str.toUpperCase().split((""+character).toUpperCase()).length - 1;
}
Then use this method as shown below:
b = string.count('H');
b = string.count('A');
Related
I'm trying to use utilize a space " " to separate words within a String that a user inputs. For this example, the user input String might be "Random Access Memory" or "Java Development Kit." Regardless of the entered string, the space will separate each word. In addition to this, I cannot use .split or an array, since those are the most common solutions I have found thus far. Only utilizing .substring is allowed. In my failed attempts, I have only been capable of obtaining the first inputted word (ex. "Random"), but cannot separate the second and third words (ex. "Access Memory"). I'm not going to publish my failed attempts, but am asking if you could please provide the code for separating both the second and third words entered? Thanks.
P.S. I know this is used to create acronyms, I can do that part, just need to identify each substring.
import javax.swing.*;
public class ThreeLetterAcronym
{
public static void main(String[] args)
{
String wordsInput, initialInput;
String first = "";
String second = "";
String third = "";
int firstWord;
int secondWord;
int wordLength;
int secondWordLength;
char c;
wordsInput = JOptionPane.showInputDialog(null, "Please enter three words");
initialInput = wordsInput;
wordLength = wordsInput.length();
firstWord = 0;
secondWord = 0;
while(firstWord < wordsInput.length())
{
if(wordsInput.charAt(firstWord) == ' ')
{
first = wordsInput.substring(0,firstWord);
second = wordsInput.substring(firstWord + 1, wordsInput.length());
//I know that this is the spot where the last two words are displayed in the output, this is
//the closest I have been to displaying anything relevant.
firstWord = wordsInput.length();
}
++firstWord;
}
JOptionPane.showMessageDialog(null, "Original phrase was: "
+ initialInput + "\nThree letter acronym is: " + first + second);
}
}
Just to separate in words without (strangely) using Spring.split:
String myString = "Random Access Memory";
int begin = 0;
int end;
while((end = myString.indexOf(" ", begin)) != -1) {
System.out.println(myString.substring(begin, end));
begin = end + 1;
}
System.out.println(myString.substring(begin));
String tmp = wordsInput.trim();
int spaceIndex = tmp.indexOf(" ");
first = tmp.substring(0,spaceIndex);
tmp = tmp.substring(spaceIndex+1);
tmp = tmp.trim();
spaceIndex = tmp.indexOf(" ");
second = tmp.substring(0, spaceIndex);
tmp = tmp.trim();
third = tmp.substring(spaceIndex+1);
You can use a loop to improve the code. I hope that will be helpful.
So I have this program I need to write. I'm, supposed to get an input string from a user and then print out how many capital letters and how many lowercased letters are in the string. I've looked everywhere in the book that I have and I just can't seem to find anything about how to print out the uppercase and lowercase letters. I've been doing a lot of googling as well and I couldn't find anything useful.
Anyway here's my code:
import java.util.Scanner; //calls out the method to get input from user
public class Verk1 {
public static void main(String args[])
{
Scanner innslattur = new Scanner(System.in); //input gotten from user
System.out.println("Sláðu inn textabrot í há- og lágstöfum.");
System.out.println("Forritið mun þá segja þér hve margir stafir eru af hverri gerð.");
System.out.println("Textabrot: ");
//The printouts before tell the user to enter in a string, the program will then print out //how many upper- and lowercase letters there are.
String strengur = innslattur.nextLine();
String hastafir = "";
for (int i=0; i<hastafir.length();i++);
{
System.out.println("Í textabrotinu eru " + hastafir + " hástafir");
}
}
}
I know the code is faulty/doesn't work, but do any of you know how I get the number of uppercase- lowercase letters to print them out?
Thanks in advance!
Cheers
I haven't tested it but I would look to do something like this.
String text = "This IS My TEXT StrinG";
int upperCaseCounter = 0;
int lowerCaseCounter = 0;
for (int i=0; i<text.length(); i++)
{
if (Character.isUpperCase(text.charAt(i)))
{
upperCaseCounter++;
}
else if(Character.isLowerCase(text.charAt(i)))
{
lowerCaseCounter++;
}
}
System.out.println("Total Uppercase Characters: " + upperCaseCounter);
System.out.println("Total Lowercase Characters: " + lowerCaseCounter);
You can do their fairly easily if you convert the string to a char[] first. You can then use the isUpperCase(char c) for each character in the string. http://www.tutorialspoint.com/java/character_isuppercase.htm
For some strange reason your for loop is referring to an empty string you've just declared, rather than the string you just read in from the user. However, if you change that, inside your loop you can get at the individual characters in the string with strengur.charAt(i) and you can test whether a letter is capital with Character.isUpperCase(ch) and you can check for a lower case letter with Character.isLowerCase(ch).
public void printCapsAndLowercaseCounts(String s) {
int uppercase = 0;
int lowercase = 0;
if (s != null) {
String s1 = s.toUpperCase();
String s2 = s.toLowerCase();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == s1.charAt(i) ^ s.charAt(i) == s2.charAt(i)) {
if (s.charAt(i) == s1.charAt(i)) uppercase++;
else lowercase++;
}
}
}
System.out.println(uppercase + " " + lowercase);
}
Seems like this would do the trick, assuming you're not doing it an excessive amount. Just use a temporary string, and get the difference between the two:
int capLetterCount = originalString.length() - originalString.replaceAll("[A-Z]", "").length();
I have a string, for ex:
There exists a word *random*.
random will be a random word.
How can I use a regular expression to replace every character of random with * and have this result:
There exists a word ********.
So the * replaces every character, in this case 6 characters.
Notice that I am after to replace only the word random, not the surroundings *.
So far I have:
str.replaceAll("(\\*)[^.]*(\\*)", "\\*");
But it replaces *random* with *, instead of the desired ******** (total of 8).
Any help, really appreciated...
If you have just a single word like that: -
As far as current example is concerned, if you are having just a single word like that, then you can save yourself from regex, by using some String class methods: -
String str = "There exists a word *random*.";
int index1 = str.indexOf("*");
int index2 = str.indexOf("*", index1 + 1);
int length = index2 - index1 - 1; // Get length of `random`
StringBuilder builder = new StringBuilder();
// Append part till start of "random"
builder.append(str.substring(0, index1 + 1));
// Append * of length "random".length()
for (int i = 0; i < length; i++) {
builder.append("*");
}
// Append part after "random"
builder.append(str.substring(index2));
str = builder.toString();
If you can have multiple words like that: -
For that, here's a regex solution (This is where it starts getting a little complex): -
String str = "There exists a word *random*.";
str = str.replaceAll("(?<! ).(?!([^*]*[*][^*]*[*])*[^*]*$)", "*");
System.out.println(str);
The above pattern replaces all the characters that is not followed by string containing even numbers of * till the end, with a *.
Whichever is appropriate for you, you can use.
I'll add an explanation of the above regex: -
(?<! ) // Not preceded by a space - To avoid replacing first `*`
. // Match any character
(?! // Not Followed by (Following pattern matches any string containing even number of stars. Hence negative look-ahead
[^*]* // 0 or more Non-Star character
[*] // A single `star`
[^*]* // 0 or more Non-star character
[*] // A single `star`
)* // 0 or more repetition of the previous pattern.
[^*]*$ // 0 or more non-star character till the end.
Now the above pattern will match only those words, which are inside a pair of stars. Provided you don't have any unbalanced stars.
You can extract the word between * and do a replaceAll characters with * on it.
import java.util.regex.*;
String txt = "There exists a word *random*.";
// extract the word
Matcher m = Pattern.compile("[*](.*?)[*]").matcher(txt);
if (m.find()) {
// group(0): *random*
// group(1): random
System.out.println("->> " + m.group(0));
txt = txt.replace(m.group(0), m.group(1).replaceAll(".", "*"));
}
System.out.println("-> " + txt);
You can see it on ideone: http://ideone.com/VZ7uMT
try
String s = "There exists a word *random*.";
s = s.replaceAll("\\*.+\\*", s.replaceAll(".*(\\*.+\\*).*", "$1").replaceAll(".", "*"));
System.out.println(s);
output
There exists a word ********.
public static void main(String[] args) {
String str = "There exists a word *random*.";
Pattern p = Pattern.compile("(\\*)[^.]*(\\*)");
java.util.regex.Matcher m = p.matcher(str);
String s = "";
if (m.find())
s = m.group();
int index = str.indexOf(s);
String copy = str;
str = str.substring(0, index);
for (int i = index; i < index + s.length(); i++) {
str = str + "*";
}
str = str + copy.substring(index + s.length(), copy.length());
System.out.println(str);
}
String lower = Name.toLowerCase();
int a = Name.indexOf(" ",0);
String first = lower.substring(0, a);
String last = lower.substring(a+1);
char f = first.charAt(0);
char l = last.charAt(0);
f = Character.toUpperCase(f);
l = Character.toUpperCase(l);
String newname = last +" "+ first;
System.out.println(newname);
i want to take variables F and L and replace the lowercase first letters in last and first so they will be uppercase. How can I do this? i want to just replace the first letter in the last and first name with the char first and last
if you are trying to do what i think you are, you should consider using the apache commons-lang library, then look at:
WordUtils.capitalize
obviously, this is also open source, so for the best solution to your homework i'd take a look at the source code.
However, if i were writing it from scratch (and optimum performance wasn't the goal) here's how i would approach it:
public String capitalize(String input)
{
// 1. split on the negated 'word' matcher (regular expressions)
String[] words = input.toLowerCase().split("\\W");
StringBuffer end = new StringBuffer();
for (String word : words)
{
if (word.length == 0)
continue;
end.append(" ");
end.append(Character.toUpperCase(word.charAt(0)));
end.append(word.substring(1));
}
// delete the first space character
return end.deleteCharAt(0).toString();
}
While there's more efficient ways of doing this, you almost got it. You'd just need to concatenate the uppercase chars with the first and last name, bar the first character.
String newname = "" + l + last.subString(1) + " " + f + first.subString(1);
EDIT:
You could also use a string tokenizer to get the names as in:
StringTokenizer st = new StringTokenizer(Name);
String fullName = "";
String currentName;
while (st.hasMoreTokens()) {
/* add spaces between each name */
if(fullName != "") fullName += " ";
currentName = st.nextToken();
fullName += currentName.substring(0,0).toUpperCase() + currentName.substring(1);
}
String name = "firstname lastname";
//match with letter in beginning or a letter after a space
Matcher matcher = Pattern.compile("^\\w| \\w").matcher(name);
StringBuffer b=new StringBuffer();
while(matcher.find())
matcher.appendReplacement(b,matcher.group().toUpperCase());
matcher.appendTail(b);
name=b.toString();//Modified Name
What is the best way to extract the integer part of a string like
Hello123
How do you get the 123 part. You can sort of hack it using Java's Scanner, is there a better way?
As explained before, try using Regular Expressions. This should help out:
String value = "Hello123";
String intValue = value.replaceAll("[^0-9]", ""); // returns 123
And then you just convert that to an int (or Integer) from there.
I believe you can do something like:
Scanner in = new Scanner("Hello123").useDelimiter("[^0-9]+");
int integer = in.nextInt();
EDIT: Added useDelimiter suggestion by Carlos
Why don't you just use a Regular Expression to match the part of the string that you want?
[0-9]
That's all you need, plus whatever surrounding chars it requires.
Look at http://www.regular-expressions.info/tutorial.html to understand how Regular expressions work.
Edit: I'd like to say that Regex may be a little overboard for this example, if indeed the code that the other submitter posted works... but I'd still recommend learning Regex's in general, for they are very powerful, and will come in handy more than I'd like to admit (after waiting several years before giving them a shot).
Assuming you want a trailing digit, this would work:
import java.util.regex.*;
public class Example {
public static void main(String[] args) {
Pattern regex = Pattern.compile("\\D*(\\d*)");
String input = "Hello123";
Matcher matcher = regex.matcher(input);
if (matcher.matches() && matcher.groupCount() == 1) {
String digitStr = matcher.group(1);
Integer digit = Integer.parseInt(digitStr);
System.out.println(digit);
}
System.out.println("done.");
}
}
I had been thinking Michael's regex was the simplest solution possible, but on second thought just "\d+" works if you use Matcher.find() instead of Matcher.matches():
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Example {
public static void main(String[] args) {
String input = "Hello123";
int output = extractInt(input);
System.out.println("input [" + input + "], output [" + output + "]");
}
//
// Parses first group of consecutive digits found into an int.
//
public static int extractInt(String str) {
Matcher matcher = Pattern.compile("\\d+").matcher(str);
if (!matcher.find())
throw new NumberFormatException("For input string [" + str + "]");
return Integer.parseInt(matcher.group());
}
}
Although I know that it's a 6 year old question, but I am posting an answer for those who want to avoid learning regex right now(which you should btw). This approach also gives the number in between the digits(for eg. HP123KT567 will return 123567)
Scanner scan = new Scanner(new InputStreamReader(System.in));
System.out.print("Enter alphaNumeric: ");
String x = scan.next();
String numStr = "";
int num;
for (int i = 0; i < x.length(); i++) {
char charCheck = x.charAt(i);
if(Character.isDigit(charCheck)) {
numStr += charCheck;
}
}
num = Integer.parseInt(numStr);
System.out.println("The extracted number is: " + num);
This worked for me perfectly.
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("string1234more567string890");
while(m.find()) {
System.out.println(m.group());
}
OutPut:
1234
567
890
String[] parts = s.split("\\D+"); //s is string containing integers
int[] a;
a = new int[parts.length];
for(int i=0; i<parts.length; i++){
a[i]= Integer.parseInt(parts[i]);
System.out.println(a[i]);
}
We can simply use regular expression to extract the integer value from string
String str= "HEll1oTe45st23";
String intValue = str.replaceAll("[^0-9]", "");
System.out.print(Integer.parseInt(intValue));
Here, you can replaceAll string values with empty values and then parse the string to integer value. Further, you can use integer values.