trouble with CharAt - java

I am suppose to make a simple program that would take a users input, and put spaces between each single letter. So for example, user enters mall, and it returns M A L L(on same line).
I am trying to make a loop with a if statement in it.But I think I would need CharAt for it, so if the string is greater value then 1, I would declare a variable to everysingle character in the string(that the userinput). Then I would say put spaces between each letter. I am in AP computer science A, and we are practicing loops.Everything underthis, is what I have done so far. And the directions are in the comment above code.And im useing eclipse,java.
/**
* Splits the string str into individual characters: Small becomes S m a l l
*/
public static String split(String str) {
for (int i = 0; str.length() > i; i++) {
if (str.length() > 0) {
char space = str.charAt();
}
}
return str;
}

My solution uses concat to build the str2, and trim to remove last white space.
public static String split(String str) {
String str2 = "";
for(int i=0; i<str.length(); i++) {
str2 = str2.concat(str.charAt(i)+" ");
}
return str2.trim();
}

You don't modify method parameters, you make copies of them.
You don't null-check/empty-check inside the loop, you do it first thing in the method.
The standard in a for loop is i < size, not size > i... meh
/**
* Splits the string str into individual characters: Small becomes S m a l l
*/
public static String split(final String str)
{
String result = "";
// If parameter is null or empty, return an empty string
if (str == null || str.isEmpty())
return result;
// Go through the parameter's characters, and modify the result
for (int i = 0; i < str.length(); i++)
{
// The new result will be the previous result,
// plus the current character at position i,
// plus a white space.
result = result + str.charAt(i) + " ";
}
return result;
}
4. Go pro, use StringBuilder for the result, and static final constants for empty string and space character.
Peace!

Ask yourself a question, where is s coming from?
char space = s.charAt(); ??? s ???
A second question, character at?
public static String split(String str){
for(int i = 0; i < str.length(); i++) {
if (str.length() > 0) {
char space = str.charAt(i)
}
}
return str;
}

#Babanfaraj, this a answer from a newbie like you!!
The code is very easy. The corrected program is-
class fopl
{
public static void main(String str)
{
int n=str.length();
for (int i = 0;i<n; i++)
{
if (n>=0)
{
String space = str.charAt(i)+" ";
System.out.print(space);
}
}
}
}
Happy to help you!

Related

Reverse words without changing capitals or punctuation

Create a program with the lowest amount of characters to reverse each word in a string while keeping the order of the words, as well as punctuation and capital letters, in their initial place.
By "Order of the words", I mean that each word is split by an empty space (" "), so contractions and such will be treated as one word. The apostrophe in contractions should stay in the same place. ("Don't" => "Tno'd").
(Punctuation means any characters that are not a-z, A-Z or whitespace*).
Numbers were removed from this list due to the fact that you cannot have capital numbers. Numbers are now treated as punctuation.
For example, for the input:
Hello, I am a fish.
it should output:
Olleh, I ma a hsif.
Notice that O, which is the first letter in the first word, is now capital, since H was capital before in the same location.
The comma and the period are also in the same place.
More examples:
This; Is Some Text!
would output
Siht; Si Emos Txet!
I've tried this:
public static String reverseWord(String input)
{
String words[]=input.split(" ");
StringBuilder result=new StringBuilder();
for (String string : words) {
String revStr = new StringBuilder(string).reverse().toString();
result.append(revStr).append(" ");
}
return result.toString().trim();
}
I have tried to solve your problem. It's working fine for the examples I have checked :) Please look and let me know :)
public static void main(String[] args) {
System.out.println(reverseWord("This; Is Some Text!"));
}
public static boolean isAlphaNumeric(String s) {
return s != null && s.matches("^[a-zA-Z0-9]*$");
}
public static String reverseWord(String input)
{
String words[]=input.split(" ");
StringBuilder result=new StringBuilder();
int startIndex = 0;
int endIndex = 0;
for(int i = 0 ; i < input.length(); i++) {
if (isAlphaNumeric(Character.toString(input.charAt(i)))) {
endIndex++;
} else {
String string = input.substring(startIndex, endIndex);
startIndex = ++endIndex;
StringBuilder revStr = new StringBuilder("");
for (int j = 0; j < string.length(); j++) {
char charToAdd = string.charAt(string.length() - j - 1);
if (Character.isUpperCase(string.charAt(j))) {
revStr.append(Character.toUpperCase(charToAdd));
} else {
revStr.append(Character.toLowerCase(charToAdd));
}
}
result.append(revStr);
result.append(input.charAt(i));
}
}
if(endIndex>startIndex) // endIndex != startIndex
{
String string = input.substring(startIndex, endIndex);
result.append(string);
}
return result.toString().trim();
}
Call the reverseWord with your test string.
Hope it helps. Don't forget to mark it as right answer, if it is :)
Here is a proposal that follows your requirements. It may seem very long but its just comments and aerated code; and everybody loves comments.
public static String smartReverseWords(String input) {
StringBuilder finalString = new StringBuilder();
// Word accumulator, resetted after each "punctuation" (or anything different than a letter)
StringBuilder wordAcc = new StringBuilder();
int processedChars = 0;
for(char c : input.toCharArray()) {
// If not a whitespace nor the last character
if(!Character.isWhitespace(c)) {
// Accumulate letters
wordAcc.append(c);
// Have I reached the last character? Then finalize now:
if(processedChars == input.length()-1) {
reverseWordAndAppend(wordAcc, finalString);
}
}
else {
// Was a word accumulated?
if(wordAcc.length() > 0) {
reverseWordAndAppend(wordAcc, finalString);
}
// Append non-letter char to final string:
finalString.append(c);
}
processedChars++;
}
return finalString.toString();
}
private static void reverseWordAndAppend(StringBuilder wordAcc, StringBuilder finalString) {
// Then reverse it:
smartReverse(wordAcc); // a simple wordAcc.reverse() is not possible
// Append word to final string:
finalString.append(wordAcc.toString());
// Reset accumulator
wordAcc.setLength(0);
}
private static class Marker {
Integer position;
String character;
}
private static void smartReverse(StringBuilder wordAcc) {
char[] arr = wordAcc.toString().toCharArray();
wordAcc.setLength(0); // clean it for now
// Memorize positions of 'punctuation' + build array free of 'punctuation' in the same time:
List<Marker> mappedPosOfNonLetters = new ArrayList<>(); // order matters
List<Integer> mappedPosOfCapitals = new ArrayList<>(); // order matters
for (int i = 0; i < arr.length; i++) {
char c = arr[i];
if(!Character.isLetter(c)) {
Marker mark = new Marker();
mark.position = i;
mark.character = c+"";
mappedPosOfNonLetters.add(mark);
}
else {
if(Character.isUpperCase(c)) {
mappedPosOfCapitals.add(i);
}
wordAcc.append(Character.toLowerCase(c));
}
}
// Reverse cleansed word:
wordAcc.reverse();
// Reintroduce 'punctuation' at right place(s)
for (Marker mark : mappedPosOfNonLetters) {
wordAcc.insert(mark.position, mark.character);
}
// Restore capitals at right place(s)
for (Integer idx : mappedPosOfCapitals) {
wordAcc.setCharAt(idx,Character.toUpperCase(wordAcc.charAt(idx)));
}
}
EDIT
I've updated the code to take all your requirements into account. Indeed we have to make sure that "punctuation' stay in place (and capitals also) but also within a word, like a contraction.
Therefore given the following input string:
"Hello, I am on StackOverflow. Don't tell anyone."
The code produces this output:
"Olleh, I ma no WolfrEvokcats. Tno'd llet enoyna."

Counting the number of specific occurrences in a java String

I am attempting to solve a problem where I create a method that counts the number of occurrences of capital and lowercase ("A" or "a") in a certain string. I have been working on this problem for a week now, and the main error that I am receiving is that "char cannot be dereferenced". Can anyone point me in the correct direction on this Java problem? Thank you.
class Main{
public static int countA (String s)
{
String s1 = "a";
String s2 = "A";
int count = 0;
for (int i = 0; i < s.length; i++){
String s3 = s.charAt(i);
if (s3.equals(s1) || s3.equals(s2)){
count += 1;
}
else{
System.out.print("");
}
}
}
//test case below (dont change):
public static void main(String[] args){
System.out.println(countA("aaA")); //3
System.out.println(countA("aaBBdf8k3AAadnklA")); //6
}
}
try a simpler solution
String in = "aaBBdf8k3AAadnklA";
String out = in.replace ("A", "").replace ("a", "");
int lenDiff = in.length () - out.length ();
Also as #chris mentions in his answer, the String could be converted to lowercase first and then only do a single check
the main error that I am receiving is that "char cannot be
dereferenced"
change this:
s.length // this syntax is incorrect
to this:
s.length() // this is how you invoke the length method on a string
also, change this:
String s3 = s.charAt(i); // you cannot assign a char type to string type
to this:
String s3 = Character.toString(s.charAt(i)); // convert the char to string
another solution to accomplishing your task in a simpler manner is by using the Stream#filter method. Then convert each String within the Stream to lowercase prior to comparison, if any Strings match "a" we keep it, if not we ignore it and at the end, we simply return the count.
public static int countA(String input)
{
return (int)Arrays.stream(input.split("")).filter(s -> s.toLowerCase().equals("a")).count();
}
For counting the number of time 'a' or 'A' appears in a String:
public int numberOfA(String s) {
s = s.toLowerCase();
int sum = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == 'a')
sum++;
}
return sum;
}
Or just replace everything else and see how long your string is:
int numberOfA = string.replaceAll("[^aA]", "").length();
To find the number of times character a and A appear in string.
int numA = string.replaceAll("[^aA]","").length();

Substring alternative

So I'm creating a program that will output the first character of a string and then the first character of another string. Then the second character of the first string and the second character of the second string, and so on.
I created what is below, I was just wondering if there is an alternative to this using a loop or something rather than substring
public class Whatever
{
public static void main(String[] args)
{
System.out.println (interleave ("abcdefg", "1234"));
}
public static String interleave(String you, String me)
{
if (you.length() == 0) return me;
else if (me.length() == 0) return you;
return you.substring(0,1) + interleave(me, you.substring(1));
}
}
OUTPUT: a1b2c3d4efg
Well, if you really don't want to use substrings, you can use String's toCharArray() method, then you can use a StringBuilder to append the chars. With this you can loop through each of the array's indices.
Doing so, this would be the outcome:
public static String interleave(String you, String me) {
char[] a = you.toCharArray();
char[] b = me.toCharArray();
StringBuilder out = new StringBuilder();
int maxLength = Math.max(a.length, b.length);
for( int i = 0; i < maxLength; i++ ) {
if( i < a.length ) out.append(a[i]);
if( i < b.length ) out.append(b[i]);
}
return out.toString();
}
Your code is efficient enough as it is, though. This can be an alternative, if you really want to avoid substrings.
This is a loop implementation (not handling null value, just to show the logic):
public static String interleave(String you, String me) {
StringBuilder result = new StringBuilder();
for (int i = 0 ; i < Math.max(you.length(), me.length()) ; i++) {
if (i < you.length()) {
result.append(you.charAt(i)); }
if (i < me.length()) {
result.append(me.charAt(i));
}
}
return result.toString();
}
The solution I am proposing is based on the expected output - In your particular case consider using split method of String since you are interleaving by on character.
So do something like this,
String[] xs = "abcdefg".split("");
String[] ys = "1234".split("");
Now loop over the larger array and ensure interleave ensuring that you perform length checks on the smaller one before accessing.
To implement this as a loop you would have to maintain the position in and keep adding until one finishes then tack the rest on. Any larger sized strings should use a StringBuilder. Something like this (untested):
int i = 0;
String result = "";
while(i <= you.length() && i <= me.length())
{
result += you.charAt(i) + me.charAt(i);
i++;
}
if(i == you.length())
result += me.substring(i);
else
result += you.substring(i);
Improved (in some sense) #BenjaminBoutier answer.
StringBuilder is the most efficient way to concatenate Strings.
public static String interleave(String you, String me) {
StringBuilder result = new StringBuilder();
int min = Math.min(you.length(), me.length());
String longest = you.length() > me.length() ? you : me;
int i = 0;
while (i < min) { // mix characters
result.append(you.charAt(i));
result.append(me.charAt(i));
i++;
}
while (i < longest.length()) { // add the leading characters of longest
result.append(longest.charAt(i));
i++;
}
return result.toString();
}

Return word specified by the integer

I know I'm missing some things and that's what I really need help with. The code doesn't work in all cases and am looking for help improving/fixing it.
Assignment:
The code I have so far:
public String word(int num, String words)
{
int l = words.indexOf(" ");
int r = words.indexOf(" ", l+1);
for(int i = 3; i <= num; i++){
l = r;
r = words.indexOf(" ", l+1);
//if(i != num)
// l = r;
}
String theword = words.substring(l,r);
return theword;
}
}
As this is clearly homework, I will give you text only.
Your approach may work eventually, but it is laborious and overly complicated, so it's hard to debug and hard to get right.
make use of String's API by using the split() method
after splitting the sentence into an array of word Strings, return the element at num less one (array are indexed starting at zero
check the length of the array first, in case there are less words than num, and take whatever action you think is appropriate in that case
For part 2, a solution in a simple form may be:
create a new blank string for the result
iterate over the characters of the given string adding the character to the front of the result string
make use of String's toUpperCase() method
Since this is homework and you have showed some effort. This is how you can do part 1 of your question. This code is pretty evident.
1) I am returning null if number is greater than the number of words in string as we dont want user to enter 5 when there are only 2 words in a string
2) Splitting the string by space and basically returning the array with the number mentioned by user
There are more conditions which you must figure out such as telling the user to enter a number of the string length since it would not give him any result and taking input from Scanner instead of directy adding input in method.
public static String word(int num, String words)
{
String wordsArr[] = words.split(" ");
if(num <= 0 || num > wordsArr.length) return null;
return (wordsArr[num-1]);
}
the second part of your question must be attempted by you.
Well... not often you see people coming here with homework AND showing effort at the same time so bravo :).
This is example of how you can split the string and return the [x] element from that string
public class SO {
public static void main(String[] args) throws Exception {
int number = 3;
String word = "Hello this is sample code";
SO words = new SO();
words.returnWord(number, word);
}
private void returnWord(int number, String word) throws Exception {
String[] words = word.split("\\s+");
int numberOfWords = words.length;
if(numberOfWords >= number) {
System.out.println(words[number-1]);
} else {
throw new Exception("Not enought words!!!");
}
}
}
Yes it is a working example but do not just copy and paste that for your homework - as simple question from teacher - What is this doing, or how this works and your out :)! So understand the code, and try to modify it in a way that you are familiar what is doing what. Also its worth getting some Java book - and i recommend Head first Java by O'Really <- v.good beginner book!
if you have any questions please do ask!. Note that this answer is not 100% with what the textbook is asking for, so you can modify this code accordingly.
As of part 2. Well what Bohemian said will also do, but there is a lot quicker solution to this.
Look at StringBuilder(); there is a method on it that will be of your interest.
To convert String so all letter are upper case you can use .toUpperCase() method on this reversed string :)
You can try:
public class trial {
public static void main(String[] args)
{
System.out.println(specificword(0, "yours faithfully kyobe"));
System.out.println(reverseString("derrick"));}
public static String specificword(int number, String word){
//split by space
String [] parts = word.split("\\ ");
if(number <= parts.length){
return parts[number];
}
else{
return "null String";
}
}
public static String reverseString(String n){
String c ="";
for(int i = n.length()-1; i>=0; i--){
char m = n.charAt(i);
c = c + m;
}
String m = c.toUpperCase();
return m;
}
}
For the first problem, I'll give you two approaches (1. is recommended):
Use the String.split method to split the words up into an array of words, where each element is a word. Instead of one string containing all of the words, such as "hello my name is Michael", it will create an array of the words, like so [hello, my, name, is, Michael] and that way you can use the array to access the words. Very easy:
public static String word(int num, String words)
{
// split words string into array by the spaces
String[] wordArray = words.split(" "); // or = words.split("\\s+");
// if the number is within the range
if (num > 0 && num <= wordArray.length) {
return wordArray[num - 1]; // return the word from the word array
} else { // the number is not within the range of words
return null;
}
}
Only use this if you cannot use arrays! Loop through the word until you have found enough spaces to match the word you want to find:
public static String word(int num, String words)
{
for (int i = 0; i < words.length(); i++) { // every character in words
if (words.substring(i, i+1).equals(" ")) { // if word is a space
num = num - 1; // you've found the next word, so subtract 1 (number of words left is remaining)
}
if (num == 1) { // found all words
// return this word
int lastIndex = i+1;
while (lastIndex < words.length()) { // until end of words string
if (words.substring(lastIndex, lastIndex+1).equals(" ")) {
break;
}
lastIndex = lastIndex + 1; // not a space so keep moving along the word
}
/*
// or you could use this to find the last index:
int lastIndex = words.indexOf(" ", i + 1); // next space after i+1
if (lastIndex == -1) { // couldn't find another space
lastIndex = words.length(); // so just make it the last letter in words
}*/
if (words.substring(i, i+1).equals(" ")) { // not the first word
return words.substring(i+1, lastIndex);
} else {
return words.substring(i, lastIndex);
}
}
}
return null; // didn't find word
}
As for the second problem, just iterate backwards through the string and add each letter to a new string. You add each letter from the original string to a new string, but just back to front. And you can use String.toUpperCase() to convert the string to upper case. Something like this:
public static String reverse(String str) {
String reversedString = ""; // this will be the reversed string
// for every character started at the END of the string
for (int i = str.length() - 1; i > -1; i--) {
// add it to the reverse string
reversedString += str.substring(i, i+1);
}
return reversedString.toUpperCase(); // return it in upper case
}

write a code to find the number of words in a string using methods

I've been looking and I can't find anywhere how to write a word count using 3 methods. Here is what the code looks like so far. I'm lost on how to use the methods. I can do this without using different methods and just using one. Please help!!!
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Enter a string: ");
String s = in.nextLine();
if (s.length() > 0)
{
getInputString(s);
}
else
{
System.out.println("ERROR - string must not be empty.");
System.out.print("Enter a string: ");
s = in.nextLine();
}
// Fill in the body with your code
}
// Given a Scanner, prompt the user for a String. If the user enters an empty
// String, report an error message and ask for a non-empty String. Return the
// String to the calling program.
private static String getInputString(String s) {
int count = getWordCount();
while (int i = 0; i < s.length(); i++)
{
if (s.charAt(i) == " ")
{
count ++;
}
}
getWordCount(count);
// Fill in the body
// NOTE: Do not declare a Scanner in the body of this method.
}
// Given a String return the number of words in the String. A word is a sequence of
// characters with no spaces. Write this method so that the function call:
// int count = getWordCount("The quick brown fox jumped");
// results in count having a value of 5. You will call this method from the main method.
// For this assignment you may assume that
// words will be separated by exactly one space.
private static int getWordCount(String input) {
// Fill in the body
}
}
EDIT:
I have changed the code to
private static String getInputString(String s) {
String words = getWordCount(s);
return words.length();
}
private static int getWordCount(String s) {
return s.split(" ");
}
But I can't get the string convert to integer.
You have read the name of the method, and look at the comments to decide what should be implemented inside the method, and the values it should return.
The getInputString method signature should be:
private static String getInputString(Scanner s) {
String inputString = "";
// read the input string from system in
// ....
return inputString;
}
The getWordCount method signature should be:
private static int getWordCount(String input) {
int wordCount = 0;
// count the number of words in the input String
// ...
return wordCount;
}
The main method should look something like this:
public static void main(String[] args) {
// instantiate the Scanner variable
// call the getInputString method to ... you guessed it ... get the input string
// call the getWordCount method to get the word count
// Display the word count
}
count=1 //last word must be counted
for(int i=0;i<s.length();i++)
{
ch=s.charAt(i);
if(ch==' ')
{
count++;
}
}
Use trim() and split() on 1-n whitespace chars:
private static int getWordCount(String s) {
return s.trim().split("\\s+").length;
}
The call to trim() is necessary, otherwise you'll get one extra "word" if there is leading spaces in the string.
The parameter "\\s+" is necessary to count multiple spaces as a single word separator. \s is the regex for "whitespace". + is regex for "1 or more".
What you need to do is, count the number of spaces in the string. That is the number of words in the string.
You will see your count will be off by 1, but after some pondering and bug hunting you will figure out why.
Happy learning!
You can do this by :
private static int getWordCount(String input) {
return input.split("\\s+").length;
}
Use String.split() method like :
String[] words = s.split("\\s+");
int wordCount = words.length;
I'm not sure what trouble you're having with methods but I dont think you need more than one, try this: it uses split to split up the words in a string, and you can chose the delimeters
String sentence = "This is a sentence.";
String[] words = sentence.split(" ");
for (String word : words) {
System.out.println(word);
}
then you can do:
numberOfWords = words.length();
if you want to use 3 methods, you can call a method from your main() method that does this for you, for example:
public String getInputString() {
Scanner in = new Scanner (System.in);
System.out.print("Enter a string: ");
String s = in.nextLine();
if (s.length() > 0) {
return s;
} else {
System.out.println("ERROR - string must not be empty.");
System.out.print("Enter a string: ");
return getInputString();
}
}
public int wordCount(String s) {
words = splitString(s)
return words.length();
}
public String[] splitString(String s) {
return s.split(" ");
}
Based on your code i think this is what you're trying to do:
private static int getWordCount(String input) {
int count = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ' ') {
count++;
}
}
return count;
}
Here's what I've done:
I've moved the code you were 'playing' with into the right method (getWordCount).
Corrected the loop you were trying to use (I think you have for and while loops confused)
Fixed your check for the space character (' ' not " ")
There is a bug in this code which you'll need to work out how to fix:
getWordCount("How are you"); will return 2 when it should be 3
getWordCount(""); will return 0
getWordCount("Hello"); will return 0 when it should be 1
Good luck!
Better use simple function of spilt() with arguments as space
int n= str.split(" ").length;
public static int Repeat_Words(String arg1,String arg2)
{
//It find number of words can be formed from a given string
if(arg1.length() < 1 || arg2.length() < 1)
return 0;
int no_words = 99999;
char[] str1 = arg1.toCharArray();
char[] str2 = arg2.toCharArray();
for(int x = 0; x < str1.length; x++)
{
int temp = 0;
for(int y = 0; y < str2.length; y++)
{
if(str1[x] == str2[y])
temp++;
}
if(temp == 0)
return 0;
if(no_words > temp)
no_words = temp;
temp = 0;
}
return no_words;
}

Categories

Resources