Related
The goal of this program is to prompt the user for a single character and a phrase, and then replace any instances of that character within that phrase with a '$'. My program below does just that, but when I showed it to my professor I was told that I cannot use .replace in the methods I built, so I have to figure out a way to not use that. I have worked at it for a while, and thus far I know that I can replace it with a for loop, but after several frustrating iterations, I can't seem to get it right. Excuse me if my code looks funky, I am still an introductory java student so I'm still learning the basics. I have provided a proposed solution at the end of my code snippet below.
public static char getKeyCharacter(String userInput) {
char keyCharacter;
Scanner inputStream = new Scanner(System.in);
while(userInput.length() > 1)
{
System.out.println("Please enter a SINGLE character to use as key: ");
userInput = inputStream.nextLine();
}
keyCharacter = userInput.charAt(0);
return keyCharacter;
}
public static String getString(String userResponse) {
Scanner inputStream = new Scanner(System.in);
String theString;
while(userResponse.length() > 500) {
System.out.println("Please enter a phrase or sentence >= 4 and <=500 characters: ");
userResponse = inputStream.nextLine();
}
while(userResponse.length() < 4) {
System.out.println("Please enter a phrase or sentence >= 4 and <=500 characters: ");
userResponse = inputStream.nextLine();
}
theString = userResponse;
return theString;
}
public static String maskCharacter(String theString, char keyCharacter){
String maskedString = "";
final char mask = '$';
maskedString = maskedString + theString.replace(keyCharacter, mask);
System.out.println("String with " + keyCharacter + " masked: ");
return maskedString;
}
public static String removeCharacter(String theString, char keyCharacter) {
String modifiedString = " ";
final char replaceChar = ' ';
modifiedString = modifiedString + theString.replace(keyCharacter, replaceChar);
System.out.println("String with " + keyCharacter + " removed:");
return modifiedString;
}
public static int countKey(String theString, char keyCharacter) {
int charCount = 0;
for (int c = 0; c < theString.length(); c++) {
if (theString.charAt(c) == keyCharacter) {
charCount++;
}
}
System.out.println("Occurences of " + keyCharacter + " in string:");
return charCount;
}
}
I believe the solution is will look something like this, but thus far I've been unsuccesful -
public static String maskCharacter(String theString, char keyCharacter){
String maskedString = "";
final char mask = '$';
for (int k = 0; k < theString.length(); k++) {
if (theString.charAt(k) == keyCharacter) {
keyCharacter = mask;
}
System.out.println("String with " + keyCharacter + " masked: ");
return maskedString;
}
My issue lies in making the maskedString = theString with all the keyCharacters replaced by mask. For the record, I have yet to learn anything about those fancy arrays, so if there is a way to do this using a simple for loop I would greatly appreciate it. Thank you for the assistance in advance!
I would use a StringBuilder and String#toCharArray() with a simple for-each loop. Like,
public static String maskCharacter(String theString, char keyCharacter){
StringBuilder sb = new StringBuilder();
for (char ch : theString.toCharArray()) {
if (ch == keyCharacter) {
sb.append('$'); // <-- mask keyCharacter(s).
} else {
sb.append(ch); // <-- it isn't the character to mask
}
}
return sb.toString();
}
I wouldn't use a StringBuilder: just use the result of toCharArray() directly:
char[] cs = theString.toCharArray();
for (int i = 0; i < cs.length; ++i) {
if (cs[i] == keyCharacter) cs[i] = '$';
}
return new String(cs);
Not only is it more concise, but:
It will run faster, because it's cheaper to access an array element than to invoke a method; and because it doesn't require StringBuilder's internal buffer to resize (although you could just pre-size that);
It will use less memory, because it doesn't require storage for the copy inside StringBuilder.
public static String maskCharacter(String theString, char keyCharacter){
String masked = "";
for (int i = 0 ; i < theString.length() ; i++) {
if (theString.charAt(i) == keyCharacter) {
masked += "$";
}
else {
masked+=theString.charAt(i)+"";
}
}
return masked;
}
An answer that only uses string concatenation and basic character access.
You seem to know that you can concatenate something to a string and get a different string.
maskedString = maskedString + ...;
You also know you can build a for-loop that gets each individual character using .charAt()
for (int k = 0; k < theString.length(); k++) {
char nch = theString.charAt(k);
}
You can check equality between chars
if (nch == keyCharacter)
... assuming you know about else-branches, isn't it clear you just need to put them together?
if (nch == keyCharacter) {
// append '$' to maskedString
}
else {
// append nch to maskedString
}
Of course this creates a new string on every loop iteration so it is not terribly efficient. But I don't think that's the point of the exercise.
Hi guys I'm trying to remove white spaces using loops specifically. Heres what I've come up with so far
import java.util.Scanner;
public class Q2 {
public static void main(String[] args) {
String input = "";
char noSpace = ' ';
Scanner scan = new Scanner(System.in);
input = scan.nextLine();
System.out.println(input);
for (int i = 0; i < input.length(); i++) { //search from right to left
for (int j = input.length(); j != -1; j--) { //search from left to right
if (input.charAt(i) == noSpace) { //if there is a space move position of i and j
i++;
j--;
}
}
System.out.println(input);
I am still quite new to java, any suggestions would be great thanks!
Try this one:
public class RemoveWhiteSpace {
public static void main(String[] args) {
String str = "Hello World... Hai... How are you? .";
for(Character c : str.toCharArray()) {
if(!Character.isWhitespace(c)) // Check if not white space print the char
System.out.print(c);
}
}
}
Why you do not use regular expressions? replaceAll("\\s","") removes all whitespaces. Also you can remove other non visible symbols, such as \tab etc.
Look at docs.oracle.com for more info
And a combination of themes...
StringBuilder result = new StringBuilder(64);
String str = "sample test";
for (Character c : str.toCharArray()) {
if (!Character.isWhitespace(c)) {
result.append(c);
}
}
System.out.println(result.toString()); // toString is not required, but I've had to many people assume that StringBuilder is a String
System.out.println(str.replace(" ", ""));
System.out.println("Double spaced".replace(" ", ""));
Basically, nothing new, just runnable examples of what every body else has spoken about...
import java.util.Scanner;
public class Iterations{
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = kb.nextLine();
String temp = "";
for (int i = 0; i < s.length(); i++){ //This loops separates the string into each character
String c = s.substring(i, i+1);
if (c.equals(" ")){
System.out.print(c.trim()); //If the individual character is space then remove it with trim()
} else {
temp = temp + c; //Adds the string up into single sentence
}
}
System.out.println(temp); //Print it to have a nice line of string
}
}
I am also new to java and happen to do problems that remove spaces with only some methods and loops. Thats my solution, feel free to try it out.
public class sample {
public static void main(String[] args) {
String input = "sample test";
char noSpace = ' ';
System.out.println("String original:"+input);
for (int i = 0; i < input.length(); i++) { //search from right to left
if (input.charAt(i) != noSpace) { //if there is a space move position of i and j
System.out.print(input.charAt(i));
}
}
}
}
You've actually gone too far by keeping two loops you could do it in one only:
public static void main(String[] args) {
String input = "";
char space = ' ';
Scanner scan = new Scanner(System.in);
input = scan.nextLine();
System.out.println(input);
for (int i = 0; i < input.length(); i++) { // search from right to left char by char
if (input.charAt(i)!= space) { // if the char is not space print it.
System.out.print(input.charAt(i));
}
}
}
I am trying to make a program on word count which I have partially made and it is giving the correct result but the moment I enter space or more than one space in the string, the result of word count show wrong results because I am counting words on the basis of spaces used. I need help if there is a solution in a way that no matter how many spaces are I still get the correct result. I am mentioning the code below.
public class CountWords
{
public static void main (String[] args)
{
System.out.println("Simple Java Word Count Program");
String str1 = "Today is Holdiay Day";
int wordCount = 1;
for (int i = 0; i < str1.length(); i++)
{
if (str1.charAt(i) == ' ')
{
wordCount++;
}
}
System.out.println("Word count is = " + wordCount);
}
}
public static void main (String[] args) {
System.out.println("Simple Java Word Count Program");
String str1 = "Today is Holdiay Day";
String[] wordArray = str1.trim().split("\\s+");
int wordCount = wordArray.length;
System.out.println("Word count is = " + wordCount);
}
The ideas is to split the string into words on any whitespace character occurring any number of times.
The split function of the String class returns an array containing the words as its elements.
Printing the length of the array would yield the number of words in the string.
Two routes for this. One way would be to use regular expressions. You can find out more about regular expressions here. A good regular expression for this would be something like "\w+" Then count the number of matches.
If you don't want to go that route, you could have a boolean flag that remembers if the last character you've seen is a space. If it is, don't count it. So the center of the loop looks like this:
boolean prevCharWasSpace=true;
for (int i = 0; i < str1.length(); i++)
{
if (str1.charAt(i) == ' ') {
prevCharWasSpace=true;
}
else{
if(prevCharWasSpace) wordChar++;
prevCharWasSpace = false;
}
}
Update
Using the split technique is exactly equivalent to what's happening here, but it doesn't really explain why it works. If we go back to our CS theory, we want to construct a Finite State Automa (FSA) that counts words. That FSA may appear as:
If you look at the code, it implements this FSA exactly. The prevCharWasSpace keeps track of which state we're in, and the str1.charAt('i') is decideds which edge (or arrow) is being followed. If you use the split method, a regular expression equivalent of this FSA is constructed internally, and is used to split the string into an array.
Java does have StringTokenizer API and can be used for this purpose as below.
String test = "This is a test app";
int countOfTokens = new StringTokenizer(test).countTokens();
System.out.println(countOfTokens);
OR
in a single line as below
System.out.println(new StringTokenizer("This is a test app").countTokens());
StringTokenizer supports multiple spaces in the input string, counting only the words trimming unnecessary spaces.
System.out.println(new StringTokenizer("This is a test app").countTokens());
Above line also prints 5
You can use String.split (read more here) instead of charAt, you will get good results.
If you want to use charAt for some reason then try trimming the string before you count the words that way you won't have the extra space and an extra word
My implementation, not using StringTokenizer:
Map<String, Long> getWordCounts(List<String> sentences, int maxLength) {
Map<String, Long> commonWordsInEventDescriptions = sentences
.parallelStream()
.map(sentence -> sentence.replace(".", ""))
.map(string -> string.split(" "))
.flatMap(Arrays::stream)
.map(s -> s.toLowerCase())
.filter(word -> word.length() >= 2 && word.length() <= maxLength)
.collect(groupingBy(Function.identity(), counting()));
}
Then, you could call it like this, as an example:
getWordCounts(list, 9).entrySet().stream()
.filter(pair -> pair.getValue() <= 3 && pair.getValue() >= 1)
.findFirst()
.orElseThrow(() ->
new RuntimeException("No matching word found.")).getKey();
Perhaps flipping the method to return Map<Long, String> might be better.
Use split(regex) method. The result is an array of strings that was splited by regex.
String s = "Today is Holdiay Day";
System.out.println("Word count is = " + s.split(" ").length);
You need to read the file line by line and reduce the multiple occurences of the whitespaces appearing in your line to a single occurence and then count for the words. Following is a sample:
public static void main(String... args) throws IOException {
FileInputStream fstream = new FileInputStream("c:\\test.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
int wordcount = 0;
while ((strLine = br.readLine()) != null) {
strLine = strLine.replaceAll("[\t\b]", "");
strLine = strLine.replaceAll(" {2,}", " ");
if (!strLine.isEmpty()){
wordcount = wordcount + strLine.split(" ").length;
}
}
System.out.println(wordcount);
in.close();
}
public class wordCOunt
{
public static void main(String ar[])
{
System.out.println("Simple Java Word Count Program");
String str1 = "Today is Holdiay Day";
int wordCount = 1;
for (int i = 0; i < str1.length(); i++)
{
if (str1.charAt(i) == ' '&& str1.charAt(i+1)!=' ')
{
wordCount++;
}
}
System.out.println("Word count is = " +(str1.length()- wordCount));
}
}
public class wordCount
{
public static void main(String ar[]) throws Exception
{
System.out.println("Simple Java Word Count Program");
int wordCount = 1,count=1;
BufferedReader br = new BufferedReader(new FileReader("C:/file.txt"));
String str2 = "", str1 = "";
while ((str1 = br.readLine()) != null) {
str2 += str1;
}
for (int i = 0; i < str2.length(); i++)
{
if (str2.charAt(i) == ' ' && str2.charAt(i+1)!=' ')
{
wordCount++;
}
}
System.out.println("Word count is = " +(wordCount));
}
}
you should make your code more generic by considering other word separators as well.. such as "," ";" etc.
public class WordCounter{
public int count(String input){
int count =0;
boolean incrementCounter = false;
for (int i=0; i<input.length(); i++){
if (isValidWordCharacter(input.charAt(i))){
incrementCounter = true;
}else if (incrementCounter){
count++;
incrementCounter = false;
}
}
if (incrementCounter) count ++;//if string ends with a valid word
return count;
}
private boolean isValidWordCharacter(char c){
//any logic that will help you identify a valid character in a word
// you could also have a method which identifies word separators instead of this
return (c >= 'A' && c<='Z') || (c >= 'a' && c<='z');
}
}
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multiset;
String str="Simple Java Word Count count Count Program";
Iterable<String> words = Splitter.on(" ").trimResults().split(str);
//google word counter
Multiset<String> wordsMultiset = HashMultiset.create();
for (String string : words) {
wordsMultiset.add(string.toLowerCase());
}
Set<String> result = wordsMultiset.elementSet();
for (String string : result) {
System.out.println(string+" X "+wordsMultiset.count(string));
}
public static int CountWords(String str){
if(str.length() == 0)
return 0;
int count =0;
for(int i=0;i< str.length();i++){
if(str(i) == ' ')
continue;
if(i > 0 && str.charAt(i-1) == ' '){
count++;
}
else if(i==0 && str.charAt(i) != ' '){
count++;
}
}
return count;
}
public class CountWords
{
public static void main (String[] args)
{
System.out.println("Simple Java Word Count Program");
String str1 = "Today is Holdiay Day";
int wordCount = 1;
for (int i = 0; i < str1.length(); i++)
{
if (str1.charAt(i) == ' ' && str1.charAt(i+1)!=' ')
{
wordCount++;
}
}
System.out.println("Word count is = " + wordCount));
}
}
This gives the correct result because if space comes twice or more then it can't increase wordcount. Enjoy.
try this
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class wordcount {
public static void main(String[] args) {
String s = "India is my country. I love India";
List<String> qw = new ArrayList<String>();
Map<String, Integer> mmm = new HashMap<String, Integer>();
for (String sp : s.split(" ")) {
qw.add(sp);
}
for (String num : qw) {
mmm.put(num, Collections.frequency(qw, num));
}
System.out.println(mmm);
}
}
To count total words Or to count total words without repeat word count
public static void main(String[] args) {
// TODO Auto-generated method stub
String test = "I am trying to make make make";
Pattern p = Pattern.compile("\\w+");
Matcher m = p.matcher(test);
HashSet<String> hs = new HashSet<>();
int i=0;
while (m.find()) {
i++;
hs.add(m.group());
}
System.out.println("Total words Count==" + i);
System.out.println("Count without Repetation ==" + hs.size());
}
}
Output :
Total words Count==7
Count without Repeatation ==5
Not sure if there is a drawback, but this worked for me...
Scanner input = new Scanner(System.in);
String userInput = input.nextLine();
String trimmed = userInput.trim();
int count = 1;
for (int i = 0; i < trimmed.length(); i++) {
if ((trimmed.charAt(i) == ' ') && (trimmed.charAt(i-1) != ' ')) {
count++;
}
}
You can use this code.It may help you:
public static void main (String[] args)
{
System.out.println("Simple Java Word Count Program");
String str1 = "Today is Holdiay Day";
int count=0;
String[] wCount=str1.split(" ");
for(int i=0;i<wCount.length;i++){
if(!wCount[i].isEmpty())
{
count++;
}
}
System.out.println(count);
}
String data = "This world is mine";
System.out.print(data.split("\\s+").length);
This could be as simple as using split and count variable.
public class SplitString {
public static void main(String[] args) {
int count=0;
String s1="Hi i love to code";
for(String s:s1.split(" "))
{
count++;
}
System.out.println(count);
}
}
public class TotalWordsInSentence {
public static void main(String[] args) {
String str = "This is sample sentence";
int NoOfWOrds = 1;
for (int i = 0; i<str.length();i++){
if ((str.charAt(i) == ' ') && (i!=0) && (str.charAt(i-1) != ' ')){
NoOfWOrds++;
}
}
System.out.println("Number of Words in Sentence: " + NoOfWOrds);
}
}
In this code, There wont be any problem regarding white-space in it.
just the simple for loop. Hope this helps...
To count specified words only like John, John99, John_John and John's only. Change regex according to yourself and count the specified words only.
public static int wordCount(String content) {
int count = 0;
String regex = "([a-zA-Z_’][0-9]*)+[\\s]*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(content);
while(matcher.find()) {
count++;
System.out.println(matcher.group().trim()); //If want to display the matched words
}
return count;
}
class HelloWorld {
public static void main(String[] args) {
String str = "User is in for an interview";
int counter=0;
String arrStr[] = str.split(" ");
for (int i = 0; i< arrStr.length; i++){
String charStr = arrStr[i];
for(int j=0; j<charStr.length(); j++) {
if(charStr.charAt(j) =='i') {
counter++;
}
}
}
System.out.println("i " + counter);
}
}
public class CountWords {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string :");
String str = sc.nextLine();
System.out.println("length is string is :"+str.length());
int worldCount = 1;
for(int i=0; i<str.length(); i++){
if(str.charAt(i) == ' '){
worldCount++;
}
}
System.out.println(worldCount);
}
}
The full program working is:
public class main {
public static void main(String[] args) {
logicCounter counter1 = new logicCounter();
counter1.counter("I am trying to make a program on word count which I have partially made and it is giving the correct result but the moment I enter space or more than one space in the string, the result of word count show wrong results because I am counting words on the basis of spaces used. I need help if there is a solution in a way that no matter how many spaces are I still get the correct result. I am mentioning the code below.");
}
}
public class logicCounter {
public void counter (String str) {
String str1 = str;
boolean space= true;
int i;
for ( i = 0; i < str1.length(); i++) {
if (str1.charAt(i) == ' ') {
space=true;
} else {
i++;
}
}
System.out.println("there are " + i + " letters");
}
}
Is there a function built into Java that capitalizes the first character of each word in a String, and does not affect the others?
Examples:
jon skeet -> Jon Skeet
miles o'Brien -> Miles O'Brien (B remains capital, this rules out Title Case)
old mcdonald -> Old Mcdonald*
*(Old McDonald would be find too, but I don't expect it to be THAT smart.)
A quick look at the Java String Documentation reveals only toUpperCase() and toLowerCase(), which of course do not provide the desired behavior. Naturally, Google results are dominated by those two functions. It seems like a wheel that must have been invented already, so it couldn't hurt to ask so I can use it in the future.
WordUtils.capitalize(str) (from apache commons-text)
(Note: if you need "fOO BAr" to become "Foo Bar", then use capitalizeFully(..) instead)
If you're only worried about the first letter of the first word being capitalized:
private String capitalize(final String line) {
return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}
The following method converts all the letters into upper/lower case, depending on their position near a space or other special chars.
public static String capitalizeString(String string) {
char[] chars = string.toLowerCase().toCharArray();
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (!found && Character.isLetter(chars[i])) {
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { // You can add other chars here
found = false;
}
}
return String.valueOf(chars);
}
Try this very simple way
example givenString="ram is good boy"
public static String toTitleCase(String givenString) {
String[] arr = givenString.split(" ");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
sb.append(Character.toUpperCase(arr[i].charAt(0)))
.append(arr[i].substring(1)).append(" ");
}
return sb.toString().trim();
}
Output will be: Ram Is Good Boy
I made a solution in Java 8 that is IMHO more readable.
public String firstLetterCapitalWithSingleSpace(final String words) {
return Stream.of(words.trim().split("\\s"))
.filter(word -> word.length() > 0)
.map(word -> word.substring(0, 1).toUpperCase() + word.substring(1))
.collect(Collectors.joining(" "));
}
The Gist for this solution can be found here: https://gist.github.com/Hylke1982/166a792313c5e2df9d31
String toBeCapped = "i want this sentence capitalized";
String[] tokens = toBeCapped.split("\\s");
toBeCapped = "";
for(int i = 0; i < tokens.length; i++){
char capLetter = Character.toUpperCase(tokens[i].charAt(0));
toBeCapped += " " + capLetter + tokens[i].substring(1);
}
toBeCapped = toBeCapped.trim();
I've written a small Class to capitalize all the words in a String.
Optional multiple delimiters, each one with its behavior (capitalize before, after, or both, to handle cases like O'Brian);
Optional Locale;
Don't breaks with Surrogate Pairs.
LIVE DEMO
Output:
====================================
SIMPLE USAGE
====================================
Source: cApItAlIzE this string after WHITE SPACES
Output: Capitalize This String After White Spaces
====================================
SINGLE CUSTOM-DELIMITER USAGE
====================================
Source: capitalize this string ONLY before'and''after'''APEX
Output: Capitalize this string only beforE'AnD''AfteR'''Apex
====================================
MULTIPLE CUSTOM-DELIMITER USAGE
====================================
Source: capitalize this string AFTER SPACES, BEFORE'APEX, and #AFTER AND BEFORE# NUMBER SIGN (#)
Output: Capitalize This String After Spaces, BeforE'apex, And #After And BeforE# Number Sign (#)
====================================
SIMPLE USAGE WITH CUSTOM LOCALE
====================================
Source: Uniforming the first and last vowels (different kind of 'i's) of the Turkish word D[İ]YARBAK[I]R (DİYARBAKIR)
Output: Uniforming The First And Last Vowels (different Kind Of 'i's) Of The Turkish Word D[i]yarbak[i]r (diyarbakir)
====================================
SIMPLE USAGE WITH A SURROGATE PAIR
====================================
Source: ab 𐐂c de à
Output: Ab 𐐪c De À
Note: first letter will always be capitalized (edit the source if you don't want that).
Please share your comments and help me to found bugs or to improve the code...
Code:
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class WordsCapitalizer {
public static String capitalizeEveryWord(String source) {
return capitalizeEveryWord(source,null,null);
}
public static String capitalizeEveryWord(String source, Locale locale) {
return capitalizeEveryWord(source,null,locale);
}
public static String capitalizeEveryWord(String source, List<Delimiter> delimiters, Locale locale) {
char[] chars;
if (delimiters == null || delimiters.size() == 0)
delimiters = getDefaultDelimiters();
// If Locale specified, i18n toLowerCase is executed, to handle specific behaviors (eg. Turkish dotted and dotless 'i')
if (locale!=null)
chars = source.toLowerCase(locale).toCharArray();
else
chars = source.toLowerCase().toCharArray();
// First charachter ALWAYS capitalized, if it is a Letter.
if (chars.length>0 && Character.isLetter(chars[0]) && !isSurrogate(chars[0])){
chars[0] = Character.toUpperCase(chars[0]);
}
for (int i = 0; i < chars.length; i++) {
if (!isSurrogate(chars[i]) && !Character.isLetter(chars[i])) {
// Current char is not a Letter; gonna check if it is a delimitrer.
for (Delimiter delimiter : delimiters){
if (delimiter.getDelimiter()==chars[i]){
// Delimiter found, applying rules...
if (delimiter.capitalizeBefore() && i>0
&& Character.isLetter(chars[i-1]) && !isSurrogate(chars[i-1]))
{ // previous character is a Letter and I have to capitalize it
chars[i-1] = Character.toUpperCase(chars[i-1]);
}
if (delimiter.capitalizeAfter() && i<chars.length-1
&& Character.isLetter(chars[i+1]) && !isSurrogate(chars[i+1]))
{ // next character is a Letter and I have to capitalize it
chars[i+1] = Character.toUpperCase(chars[i+1]);
}
break;
}
}
}
}
return String.valueOf(chars);
}
private static boolean isSurrogate(char chr){
// Check if the current character is part of an UTF-16 Surrogate Pair.
// Note: not validating the pair, just used to bypass (any found part of) it.
return (Character.isHighSurrogate(chr) || Character.isLowSurrogate(chr));
}
private static List<Delimiter> getDefaultDelimiters(){
// If no delimiter specified, "Capitalize after space" rule is set by default.
List<Delimiter> delimiters = new ArrayList<Delimiter>();
delimiters.add(new Delimiter(Behavior.CAPITALIZE_AFTER_MARKER, ' '));
return delimiters;
}
public static class Delimiter {
private Behavior behavior;
private char delimiter;
public Delimiter(Behavior behavior, char delimiter) {
super();
this.behavior = behavior;
this.delimiter = delimiter;
}
public boolean capitalizeBefore(){
return (behavior.equals(Behavior.CAPITALIZE_BEFORE_MARKER)
|| behavior.equals(Behavior.CAPITALIZE_BEFORE_AND_AFTER_MARKER));
}
public boolean capitalizeAfter(){
return (behavior.equals(Behavior.CAPITALIZE_AFTER_MARKER)
|| behavior.equals(Behavior.CAPITALIZE_BEFORE_AND_AFTER_MARKER));
}
public char getDelimiter() {
return delimiter;
}
}
public static enum Behavior {
CAPITALIZE_AFTER_MARKER(0),
CAPITALIZE_BEFORE_MARKER(1),
CAPITALIZE_BEFORE_AND_AFTER_MARKER(2);
private int value;
private Behavior(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
Using org.apache.commons.lang.StringUtils makes it very simple.
capitalizeStr = StringUtils.capitalize(str);
From Java 9+
you can use String::replaceAll like this :
public static void upperCaseAllFirstCharacter(String text) {
String regex = "\\b(.)(.*?)\\b";
String result = Pattern.compile(regex).matcher(text).replaceAll(
matche -> matche.group(1).toUpperCase() + matche.group(2)
);
System.out.println(result);
}
Example :
upperCaseAllFirstCharacter("hello this is Just a test");
Outputs
Hello This Is Just A Test
With this simple code:
String example="hello";
example=example.substring(0,1).toUpperCase()+example.substring(1, example.length());
System.out.println(example);
Result: Hello
I'm using the following function. I think it is faster in performance.
public static String capitalize(String text){
String c = (text != null)? text.trim() : "";
String[] words = c.split(" ");
String result = "";
for(String w : words){
result += (w.length() > 1? w.substring(0, 1).toUpperCase(Locale.US) + w.substring(1, w.length()).toLowerCase(Locale.US) : w) + " ";
}
return result.trim();
}
Use the Split method to split your string into words, then use the built in string functions to capitalize each word, then append together.
Pseudo-code (ish)
string = "the sentence you want to apply caps to";
words = string.split(" ")
string = ""
for(String w: words)
//This line is an easy way to capitalize a word
word = word.toUpperCase().replace(word.substring(1), word.substring(1).toLowerCase())
string += word
In the end string looks something like
"The Sentence You Want To Apply Caps To"
This might be useful if you need to capitalize titles. It capitalizes each substring delimited by " ", except for specified strings such as "a" or "the". I haven't ran it yet because it's late, should be fine though. Uses Apache Commons StringUtils.join() at one point. You can substitute it with a simple loop if you wish.
private static String capitalize(String string) {
if (string == null) return null;
String[] wordArray = string.split(" "); // Split string to analyze word by word.
int i = 0;
lowercase:
for (String word : wordArray) {
if (word != wordArray[0]) { // First word always in capital
String [] lowercaseWords = {"a", "an", "as", "and", "although", "at", "because", "but", "by", "for", "in", "nor", "of", "on", "or", "so", "the", "to", "up", "yet"};
for (String word2 : lowercaseWords) {
if (word.equals(word2)) {
wordArray[i] = word;
i++;
continue lowercase;
}
}
}
char[] characterArray = word.toCharArray();
characterArray[0] = Character.toTitleCase(characterArray[0]);
wordArray[i] = new String(characterArray);
i++;
}
return StringUtils.join(wordArray, " "); // Re-join string
}
public static String toTitleCase(String word){
return Character.toUpperCase(word.charAt(0)) + word.substring(1);
}
public static void main(String[] args){
String phrase = "this is to be title cased";
String[] splitPhrase = phrase.split(" ");
String result = "";
for(String word: splitPhrase){
result += toTitleCase(word) + " ";
}
System.out.println(result.trim());
}
1. Java 8 Streams
public static String capitalizeAll(String str) {
if (str == null || str.isEmpty()) {
return str;
}
return Arrays.stream(str.split("\\s+"))
.map(t -> t.substring(0, 1).toUpperCase() + t.substring(1))
.collect(Collectors.joining(" "));
}
Examples:
System.out.println(capitalizeAll("jon skeet")); // Jon Skeet
System.out.println(capitalizeAll("miles o'Brien")); // Miles O'Brien
System.out.println(capitalizeAll("old mcdonald")); // Old Mcdonald
System.out.println(capitalizeAll(null)); // null
For foo bAR to Foo Bar, replace the map() method with the following:
.map(t -> t.substring(0, 1).toUpperCase() + t.substring(1).toLowerCase())
2. String.replaceAll() (Java 9+)
ublic static String capitalizeAll(String str) {
if (str == null || str.isEmpty()) {
return str;
}
return Pattern.compile("\\b(.)(.*?)\\b")
.matcher(str)
.replaceAll(match -> match.group(1).toUpperCase() + match.group(2));
}
Examples:
System.out.println(capitalizeAll("12 ways to learn java")); // 12 Ways To Learn Java
System.out.println(capitalizeAll("i am atta")); // I Am Atta
System.out.println(capitalizeAll(null)); // null
3. Apache Commons Text
System.out.println(WordUtils.capitalize("love is everywhere")); // Love Is Everywhere
System.out.println(WordUtils.capitalize("sky, sky, blue sky!")); // Sky, Sky, Blue Sky!
System.out.println(WordUtils.capitalize(null)); // null
For titlecase:
System.out.println(WordUtils.capitalizeFully("fOO bAR")); // Foo Bar
System.out.println(WordUtils.capitalizeFully("sKy is BLUE!")); // Sky Is Blue!
For details, checkout this tutorial.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the sentence : ");
try
{
String str = br.readLine();
char[] str1 = new char[str.length()];
for(int i=0; i<str.length(); i++)
{
str1[i] = Character.toLowerCase(str.charAt(i));
}
str1[0] = Character.toUpperCase(str1[0]);
for(int i=0;i<str.length();i++)
{
if(str1[i] == ' ')
{
str1[i+1] = Character.toUpperCase(str1[i+1]);
}
System.out.print(str1[i]);
}
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage());
}
I decided to add one more solution for capitalizing words in a string:
words are defined here as adjacent letter-or-digit characters;
surrogate pairs are provided as well;
the code has been optimized for performance; and
it is still compact.
Function:
public static String capitalize(String string) {
final int sl = string.length();
final StringBuilder sb = new StringBuilder(sl);
boolean lod = false;
for(int s = 0; s < sl; s++) {
final int cp = string.codePointAt(s);
sb.appendCodePoint(lod ? Character.toLowerCase(cp) : Character.toUpperCase(cp));
lod = Character.isLetterOrDigit(cp);
if(!Character.isBmpCodePoint(cp)) s++;
}
return sb.toString();
}
Example call:
System.out.println(capitalize("An à la carte StRiNg. Surrogate pairs: 𐐪𐐪."));
Result:
An À La Carte String. Surrogate Pairs: 𐐂𐐪.
Use:
String text = "jon skeet, miles o'brien, old mcdonald";
Pattern pattern = Pattern.compile("\\b([a-z])([\\w]*)");
Matcher matcher = pattern.matcher(text);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buffer, matcher.group(1).toUpperCase() + matcher.group(2));
}
String capitalized = matcher.appendTail(buffer).toString();
System.out.println(capitalized);
There are many way to convert the first letter of the first word being capitalized. I have an idea. It's very simple:
public String capitalize(String str){
/* The first thing we do is remove whitespace from string */
String c = str.replaceAll("\\s+", " ");
String s = c.trim();
String l = "";
for(int i = 0; i < s.length(); i++){
if(i == 0){ /* Uppercase the first letter in strings */
l += s.toUpperCase().charAt(i);
i++; /* To i = i + 1 because we don't need to add
value i = 0 into string l */
}
l += s.charAt(i);
if(s.charAt(i) == 32){ /* If we meet whitespace (32 in ASCII Code is whitespace) */
l += s.toUpperCase().charAt(i+1); /* Uppercase the letter after whitespace */
i++; /* Yo i = i + 1 because we don't need to add
value whitespace into string l */
}
}
return l;
}
package com.test;
/**
* #author Prasanth Pillai
* #date 01-Feb-2012
* #description : Below is the test class details
*
* inputs a String from a user. Expect the String to contain spaces and alphanumeric characters only.
* capitalizes all first letters of the words in the given String.
* preserves all other characters (including spaces) in the String.
* displays the result to the user.
*
* Approach : I have followed a simple approach. However there are many string utilities available
* for the same purpose. Example : WordUtils.capitalize(str) (from apache commons-lang)
*
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
public static void main(String[] args) throws IOException{
System.out.println("Input String :\n");
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
String inputString = in.readLine();
int length = inputString.length();
StringBuffer newStr = new StringBuffer(0);
int i = 0;
int k = 0;
/* This is a simple approach
* step 1: scan through the input string
* step 2: capitalize the first letter of each word in string
* The integer k, is used as a value to determine whether the
* letter is the first letter in each word in the string.
*/
while( i < length){
if (Character.isLetter(inputString.charAt(i))){
if ( k == 0){
newStr = newStr.append(Character.toUpperCase(inputString.charAt(i)));
k = 2;
}//this else loop is to avoid repeatation of the first letter in output string
else {
newStr = newStr.append(inputString.charAt(i));
}
} // for the letters which are not first letter, simply append to the output string.
else {
newStr = newStr.append(inputString.charAt(i));
k=0;
}
i+=1;
}
System.out.println("new String ->"+newStr);
}
}
Here is a simple function
public static String capEachWord(String source){
String result = "";
String[] splitString = source.split(" ");
for(String target : splitString){
result += Character.toUpperCase(target.charAt(0))
+ target.substring(1) + " ";
}
return result.trim();
}
This is just another way of doing it:
private String capitalize(String line)
{
StringTokenizer token =new StringTokenizer(line);
String CapLine="";
while(token.hasMoreTokens())
{
String tok = token.nextToken().toString();
CapLine += Character.toUpperCase(tok.charAt(0))+ tok.substring(1)+" ";
}
return CapLine.substring(0,CapLine.length()-1);
}
Reusable method for intiCap:
public class YarlagaddaSireeshTest{
public static void main(String[] args) {
String FinalStringIs = "";
String testNames = "sireesh yarlagadda test";
String[] name = testNames.split("\\s");
for(String nameIs :name){
FinalStringIs += getIntiCapString(nameIs) + ",";
}
System.out.println("Final Result "+ FinalStringIs);
}
public static String getIntiCapString(String param) {
if(param != null && param.length()>0){
char[] charArray = param.toCharArray();
charArray[0] = Character.toUpperCase(charArray[0]);
return new String(charArray);
}
else {
return "";
}
}
}
Here is my solution.
I ran across this problem tonight and decided to search it. I found an answer by Neelam Singh that was almost there, so I decided to fix the issue (broke on empty strings) and caused a system crash.
The method you are looking for is named capString(String s) below.
It turns "It's only 5am here" into "It's Only 5am Here".
The code is pretty well commented, so enjoy.
package com.lincolnwdaniel.interactivestory.model;
public class StringS {
/**
* #param s is a string of any length, ideally only one word
* #return a capitalized string.
* only the first letter of the string is made to uppercase
*/
public static String capSingleWord(String s) {
if(s.isEmpty() || s.length()<2) {
return Character.toUpperCase(s.charAt(0))+"";
}
else {
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
}
/**
*
* #param s is a string of any length
* #return a title cased string.
* All first letter of each word is made to uppercase
*/
public static String capString(String s) {
// Check if the string is empty, if it is, return it immediately
if(s.isEmpty()){
return s;
}
// Split string on space and create array of words
String[] arr = s.split(" ");
// Create a string buffer to hold the new capitalized string
StringBuffer sb = new StringBuffer();
// Check if the array is empty (would be caused by the passage of s as an empty string [i.g "" or " "],
// If it is, return the original string immediately
if( arr.length < 1 ){
return s;
}
for (int i = 0; i < arr.length; i++) {
sb.append(Character.toUpperCase(arr[i].charAt(0)))
.append(arr[i].substring(1)).append(" ");
}
return sb.toString().trim();
}
}
Here we go for perfect first char capitalization of word
public static void main(String[] args) {
String input ="my name is ranjan";
String[] inputArr = input.split(" ");
for(String word : inputArr) {
System.out.println(word.substring(0, 1).toUpperCase()+word.substring(1,word.length()));
}
}
}
//Output : My Name Is Ranjan
For those of you using Velocity in your MVC, you can use the capitalizeFirstLetter() method from the StringUtils class.
String s="hi dude i want apple";
s = s.replaceAll("\\s+"," ");
String[] split = s.split(" ");
s="";
for (int i = 0; i < split.length; i++) {
split[i]=Character.toUpperCase(split[i].charAt(0))+split[i].substring(1);
s+=split[i]+" ";
System.out.println(split[i]);
}
System.out.println(s);
package corejava.string.intern;
import java.io.DataInputStream;
import java.util.ArrayList;
/*
* wap to accept only 3 sentences and convert first character of each word into upper case
*/
public class Accept3Lines_FirstCharUppercase {
static String line;
static String words[];
static ArrayList<String> list=new ArrayList<String>();
/**
* #param args
*/
public static void main(String[] args) throws java.lang.Exception{
DataInputStream read=new DataInputStream(System.in);
System.out.println("Enter only three sentences");
int i=0;
while((line=read.readLine())!=null){
method(line); //main logic of the code
if((i++)==2){
break;
}
}
display();
System.out.println("\n End of the program");
}
/*
* this will display all the elements in an array
*/
public static void display(){
for(String display:list){
System.out.println(display);
}
}
/*
* this divide the line of string into words
* and first char of the each word is converted to upper case
* and to an array list
*/
public static void method(String lineParam){
words=line.split("\\s");
for(String s:words){
String result=s.substring(0,1).toUpperCase()+s.substring(1);
list.add(result);
}
}
}
If you prefer Guava...
String myString = ...;
String capWords = Joiner.on(' ').join(Iterables.transform(Splitter.on(' ').omitEmptyStrings().split(myString), new Function<String, String>() {
public String apply(String input) {
return Character.toUpperCase(input.charAt(0)) + input.substring(1);
}
}));
String toUpperCaseFirstLetterOnly(String str) {
String[] words = str.split(" ");
StringBuilder ret = new StringBuilder();
for(int i = 0; i < words.length; i++) {
ret.append(Character.toUpperCase(words[i].charAt(0)));
ret.append(words[i].substring(1));
if(i < words.length - 1) {
ret.append(' ');
}
}
return ret.toString();
}
This question already has answers here:
How to capitalize the first character of each word in a string
(51 answers)
Closed 3 years ago.
I have a string: "hello good old world" and i want to upper case every first letter of every word, not the whole string with .toUpperCase(). Is there an existing java helper which does the job?
Have a look at ACL WordUtils.
WordUtils.capitalize("your string") == "Your String"
Here is the code
String source = "hello good old world";
StringBuffer res = new StringBuffer();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
System.out.print("Result: " + res.toString().trim());
sString = sString.toLowerCase();
sString = Character.toString(sString.charAt(0)).toUpperCase()+sString.substring(1);
i dont know if there is a function but this would do the job in case there is no exsiting one:
String s = "here are a bunch of words";
final StringBuilder result = new StringBuilder(s.length());
String[] words = s.split("\\s");
for(int i=0,l=words.length;i<l;++i) {
if(i>0) result.append(" ");
result.append(Character.toUpperCase(words[i].charAt(0)))
.append(words[i].substring(1));
}
import org.apache.commons.lang.WordUtils;
public class CapitalizeFirstLetterInString {
public static void main(String[] args) {
// only the first letter of each word is capitalized.
String wordStr = WordUtils.capitalize("this is first WORD capital test.");
//Capitalize method capitalizes only first character of a String
System.out.println("wordStr= " + wordStr);
wordStr = WordUtils.capitalizeFully("this is first WORD capital test.");
// This method capitalizes first character of a String and make rest of the characters lowercase
System.out.println("wordStr = " + wordStr );
}
}
Output :
This Is First WORD Capital Test.
This Is First Word Capital Test.
Here's a very simple, compact solution. str contains the variable of whatever you want to do the upper case on.
StringBuilder b = new StringBuilder(str);
int i = 0;
do {
b.replace(i, i + 1, b.substring(i,i + 1).toUpperCase());
i = b.indexOf(" ", i) + 1;
} while (i > 0 && i < b.length());
System.out.println(b.toString());
It's best to work with StringBuilder because String is immutable and it's inefficient to generate new strings for each word.
Trying to be more memory efficient than splitting the string into multiple strings, and using the strategy shown by Darshana Sri Lanka. Also, handles all white space between words, not just the " " character.
public static String UppercaseFirstLetters(String str)
{
boolean prevWasWhiteSp = true;
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (Character.isLetter(chars[i])) {
if (prevWasWhiteSp) {
chars[i] = Character.toUpperCase(chars[i]);
}
prevWasWhiteSp = false;
} else {
prevWasWhiteSp = Character.isWhitespace(chars[i]);
}
}
return new String(chars);
}
String s = "java is an object oriented programming language.";
final StringBuilder result = new StringBuilder(s.length());
String words[] = s.split("\\ "); // space found then split it
for (int i = 0; i < words.length; i++)
{
if (i > 0){
result.append(" ");
}
result.append(Character.toUpperCase(words[i].charAt(0))).append(
words[i].substring(1));
}
System.out.println(result);
Output: Java Is An Object Oriented Programming Language.
Also you can take a look into StringUtils library. It has a bunch of cool stuff.
My code after reading a few above answers.
/**
* Returns the given underscored_word_group as a Human Readable Word Group.
* (Underscores are replaced by spaces and capitalized following words.)
*
* #param pWord
* String to be made more readable
* #return Human-readable string
*/
public static String humanize2(String pWord)
{
StringBuilder sb = new StringBuilder();
String[] words = pWord.replaceAll("_", " ").split("\\s");
for (int i = 0; i < words.length; i++)
{
if (i > 0)
sb.append(" ");
if (words[i].length() > 0)
{
sb.append(Character.toUpperCase(words[i].charAt(0)));
if (words[i].length() > 1)
{
sb.append(words[i].substring(1));
}
}
}
return sb.toString();
}
import java.util.Scanner;
public class CapitolizeOneString {
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print(" Please enter Your word = ");
String str=scan.nextLine();
printCapitalized( str );
} // end main()
static void printCapitalized( String str ) {
// Print a copy of str to standard output, with the
// first letter of each word in upper case.
char ch; // One of the characters in str.
char prevCh; // The character that comes before ch in the string.
int i; // A position in str, from 0 to str.length()-1.
prevCh = '.'; // Prime the loop with any non-letter character.
for ( i = 0; i < str.length(); i++ ) {
ch = str.charAt(i);
if ( Character.isLetter(ch) && ! Character.isLetter(prevCh) )
System.out.print( Character.toUpperCase(ch) );
else
System.out.print( ch );
prevCh = ch; // prevCh for next iteration is ch.
}
System.out.println();
}
} // end class
public class WordChangeInCapital{
public static void main(String[] args)
{
String s="this is string example";
System.out.println(s);
//this is input data.
//this example for a string where each word must be started in capital letter
StringBuffer sb=new StringBuffer(s);
int i=0;
do{
b.replace(i,i+1,sb.substring(i,i+1).toUpperCase());
i=b.indexOf(" ",i)+1;
} while(i>0 && i<sb.length());
System.out.println(sb.length());
}
}
package com.raj.samplestring;
/**
* #author gnagara
*/
public class SampleString {
/**
* #param args
*/
public static void main(String[] args) {
String[] stringArray;
String givenString = "ramu is Arr Good boy";
stringArray = givenString.split(" ");
for(int i=0; i<stringArray.length;i++){
if(!Character.isUpperCase(stringArray[i].charAt(0))){
Character c = stringArray[i].charAt(0);
Character change = Character.toUpperCase(c);
StringBuffer ss = new StringBuffer(stringArray[i]);
ss.insert(0, change);
ss.deleteCharAt(1);
stringArray[i]= ss.toString();
}
}
for(String e:stringArray){
System.out.println(e);
}
}
}
Here is an easy solution:
public class CapitalFirstLetters {
public static void main(String[] args) {
String word = "it's java, baby!";
String[] wordSplit;
String wordCapital = "";
wordSplit = word.split(" ");
for (int i = 0; i < wordSplit.length; i++) {
wordCapital = wordSplit[i].substring(0, 1).toUpperCase() + wordSplit[i].substring(1) + " ";
}
System.out.println(wordCapital);
}}
public String UpperCaseWords(String line)
{
line = line.trim().toLowerCase();
String data[] = line.split("\\s");
line = "";
for(int i =0;i< data.length;i++)
{
if(data[i].length()>1)
line = line + data[i].substring(0,1).toUpperCase()+data[i].substring(1)+" ";
else
line = line + data[i].toUpperCase();
}
return line.trim();
}
So much simpler with regexes:
Pattern spaces=Pattern.compile("\\s+[a-z]");
Matcher m=spaces.matcher(word);
StringBuilder capitalWordBuilder=new StringBuilder(word.substring(0,1).toUpperCase());
int prevStart=1;
while(m.find()) {
capitalWordBuilder.append(word.substring(prevStart,m.end()-1));
capitalWordBuilder.append(word.substring(m.end()-1,m.end()).toUpperCase());
prevStart=m.end();
}
capitalWordBuilder.append(word.substring(prevStart,word.length()));
Output for input: "this sentence Has Weird caps"
This Sentence Has Weird Caps