Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
So I am trying to prompt the user to enter any words into a string. Then I want to prompt them to count the number of occurrences for whatever letter they want to count. So if they enter words in a string like "this is a test" and they search "t" for example, the return would be 3 t's in the string "this is a test". I am a little confused as to where to go from here...
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String inputValue;
String s = "";
System.out.print("Enter a string of words or type done to exit: ");
inputValue = input.readLine();
System.out.print("Which letter would you like to count: ");
s = input.readLine();
int counter = 0;
I am thinking about maybe doing a for loop and do something like counter++.
Answer provided by Jean above is correct but I would like use a different method to calculate number of occurrence of a character in a String.
String string = "this is a testing string";
int count = string.length() - string.replaceAll("t", "").length();
Or
int counter = string.split("t").length - 1;
You would need to escape meta characters if you are to check character like $.
Using Apache commons-lang you could simply do
int counter = StringUtils.countMatches(s, intputValue);
But if you really want to code it, then you could use
public int count(String fullString, char valueToCount)
{
int count = 0;
for (int i=0; i < fullString.length(); i++)
{
if (fullString.charAt(i) == valueToCount)
count++;
}
return count;
}
Another solution would consist of replacing everything in your string except the input char and return the length of the trimmed string.
return s.replaceAll("[^" + inputValue + "]", "").length();
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am not sure how to approach this problem. I've seen people using arrays but after trying it, it only worked for the whole string and not each words individually.
Thanks for the help!
You can use the split method to split the string into multiple words, saved in a String array. Then, get the first and last letter using the charAt method, and then concatenate them in the correct order to get the modified word.
String a = "This is a string with multiple words";
String[] arr = a.split(" "); //splits string into an array of strings, by separating with spaces
for (int i = 0; i < arr.length; i++) //looping through each word
{
if (arr[i].length() == 1) //don't change word if it only has 1 letter
{
System.out.print(arr[i] + " ");
continue;
}
//using charAt to obtain first and last letter of each word
char firstLetter = arr[i].charAt(0);
char lastLetter = arr[i].charAt(arr[i].length()-1);
String middle = arr[i].substring(1, arr[i].length()-1); //all letters of word except first and last
arr[i] = lastLetter + middle + firstLetter; //concatenating together to create new word
System.out.print(arr[i] + " "); //printing each word after switching letters
}
You seem like a beginner to Java, so I highly recommend you read the Java documentation on the String class and its methods, as Java has some pretty thorough and relatively easy to understand documentation.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
If there is a given
Inputs
String "abcdaa/efgh/hidjk/lmno/pqrs/tuvw" and if
int slashCounter=3,
The desired Output should be -
Output: abcdaa/efgh/hidjk/lmno
(Basically if slashCounter=3 only alplabets upto 4th '/' is allowed. From fourth '/'everything is ignored. Below is the few Input and Output. (There may be any number of alphabets between '/' to '/'). Below is few more inputs
Input:
String aaabcd/efgh/hidjk/lmno/pqrs/tuvw
if int slashCounter=2
Output: aaabcd/efgh/hidjk
Input:
String aaabcd/efgh/hidjk/lmno/pqrs/tuvw
if int slashCounter=4
Output: aaabcd/efgh/hidjk/lmno/pqrs
Could someone help me with the logic of this in JAVA. Thanks in advance.
This is how you do.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// till how much we want the string
int display = sc.nextInt();
// splits the String when "/" is encounter and then stores it in 0 index and then increases the index
String aplhabets[] = input.split("/");
// to add the String we want
StringBuilder sb = new StringBuilder();
for(int i = 0 ; i <= display; i++) {
sb.append(aplhabets[i]+"/");
}
// as we dont want the last "/" of the String we just print from 0 to string length - 1, this will remove teh last "/"
System.out.print(sb.substring(0, sb.length()-1));
}
Output:
aaabcd/efgh/hidjk/lmno/pqrs/tuvw
2
aaabcd/efgh/hidjk
String aplhabets[] = input.split("/") this splits the String and puts it in the array whenever / is encounter.
sb.substring(0, sb.length()-1) this cause when we were appending String builder from he loop it's adding / in the end.
So in order to remove last / we do sb.substring(0,sb.length-1) where first parameter is start index and second index is end index
in substring(int start, int end) start in inclusive and end is exclusive.
this is how you do the problem. Suggest you learn how to use arrays and String manipulation. this will surely benefit you.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
How to write a java program to get a string as a key board input. Then count the number of letters, digits and spaces available in that string and display the count of letters, digits and spaces.
This is honestly... really, really easy and something that really should be taught to you in an introductory course or something.
Scanner scan = new Scanner(System.in);
String userInput = scan.nextLine();
You will need to put, right after package, import java.util.Scanner. To do the other thing, i.e. counting the number of characters in the String, simply invoke length().
Pass a string as an argument in this method you get count of letter, space, and digit
public void count(String str) {
int space = 0;
int digit = 0;
int letter =0;
for (int f4 = 0; f4 < str.length(); f4++) {
if (Character.isSpace(str.charAt(f4)))
space++;
if(Character.isAlphabetic(str.charAt(f4)))
letter++;
if(Character.isDigit(str.charAt(f4)))
digit++;
}
System.out.println("space = "+space+", digit = "+digit+", letter = "+letter);
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am trying write a program that accept an input and present the input with every 5th character replaced with X (count spaces also).
For example:
input: "hello my name is mario"
outpu: "hellX my Xame Xi maXio"
I only manage to replace specific letters, e.g every "m" letter.
Any help?
If you don't care about which character is at each fifth position you could use a regex.
String input = "hello my name is mario";
String output = input.replaceAll("(....).", "$1X");
System.out.printf("input : %s%noutput: %s%n", input, output);
output
input : hello my name is mario
output: hellX my Xame Xs maXio
Here is the code for you:
String test = "hello my name is mario";
String result = "";
int c = 1;
for (int i = 0; i < test.length(); i++) {
if (c++==5) {
result += "X";
c = 1;
} else {
result += test.charAt(i);
}
}
System.out.println("result = " + result);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a String with some text, f.e.
"Thisisalongwordtest and I want tocutthelongword in pieces"
Now I want to cut the to longs word in 2 pieces with a blank. The word should be cut if it's longer than 10 characters.
The result should be:
"Thisisalon gwordtest and I want tocutthelo ngword in pieces"
How can I achieve this efficiently?
are you looking for this? or I misunderstood the question?
String newString = oldStr.replaceAll("\\w{10}","$0 "))
with your example, the newString is:
Thisisalon gwordtest and I want tocutthelo ngword in pieces
Edit for Pshemo's good comment
to avoid to add space after words with exact 10 chars:
str.replaceAll("\\w{10}(?=\\w)","$0 "));
.replaceAll("(\\w{10})(?=\\w)", "$1 ")
Tested with:
test("abcde fghij klmno pqrst");
test("abcdefghijklmnopqrst");
test("abcdefghijklmnopqrstuv");
test("abcdefghij klmnopqrstuv");
test("abcdefghij klmnopqrst uv");
separate text into words. (by space)
cut long words and replace source word with new words
assemble text again
Note, that this approach will kill multiple-spaces.
(?=\w{10,}\s)(\w{10})
Should be replaced by
"\1 "
you can use replace function.
If it has number or special characters
(?=\S{10,}\s)(\S{10})
can be used.
This is the code i wrote check it once.....
public class TakingInput {
public static void main(String[] args) {
String s="Thisisalongwordtest and I want tocutthelongword in pieces";
StringBuffer sb;
String arr[]=s.split(" ");
for(int i=0;i<arr.length;i++){
if(arr[i].length()>10){
sb=new StringBuffer(arr[i]);
sb.insert(10," ");
arr[i]=new String(sb);
}
}
for(String ss: arr){
System.out.println(ss);//o/p: "Thisisalon gwordtest and I want tocutthelo ngword in pieces"
}
}
}
This code will do exactly what you want.
First create a method that splits a String if its longer than 10 chars:
String splitIfLong(String s){
if(s.length() < 11) return s + " ";
else{
String result = "";
String temp = "";
for(int i = 0; i < s.length(); i++){
temp += s.charAt(i);
if(i == 9)
temp += " ";
result += temp;
temp = "";
}
return result + " ";
}
}
Then use Scanner to read every word in the sentence seperated by a white space" ":
String s = "Thisisalongwordtest and I want tocutthelongword in pieces";
String afterSplit = "";
Scanner in = new Scanner(s);
Then call the splitIfLong() method for every word in the sentence. And add what the method returns to a new String:
while(in.hasNext())
afterSplit += splitIfLong(in.next());
Now you can use the new String as you wish. If you call:
System.out.println(afterSplit);
it will print:
Thisisalon gwordtest and I want tocutthelo ngword in pieces
Hope this helps