Writing a trim method - java

I'm writing a method to trim certain characters from a string. s1 is the actual string, and s2 is the char that you want to trim from the string. In my main method, I called:
String text = U.trim("what ?? the hell", '?');
And the rest of the code is the trim method I wrote. The problem is that whenever I put two ? marks together it only trims one of them, but if I put them apart it trims them fine. I don't know what I did wrong, and I even put print statements in the code itself to try to debug it, and if you run the code you'll see that the two question marks are at c[5] and c[6], and below the if statement if that char is a ? mark it'll replace it and print out "5;?", but I don't know why when it's comparing c[6], and the question mark it returns as false, since c[6] is a question mark. Please help.
static String trim(String s1, char s2) {
char c[] = new char[s1.length()];
String text = "";
for (int i = 0; i < s1.length(); i++) {
c[i] = s1.charAt(i);
}
for (int i = 0; i < s1.length(); i++) {
System.out.println("C" + i + ": " + c[i]);
}
for (int i = 0; i < s1.length(); i++) {
System.out.println("Start: " + i);
if (c[i] == s2) {
System.out.println(i + ";" + s2);
for (int j = i; j < s1.length(); j++) {
if (j != s1.length() - 1) {
c[j] = c[j + 1];
} else {
c[j] = '\0';
}
}
}
}
for (int i = 0; i < c.length; i++) {
text = text + c[i];
}
return text;
}
I try the pattern class, it didn't trim the question marks.
String text = "Hello ????";
text.replaceAll(Pattern.quote("?"), "");
System.out.println(text);

You can use s1.replace("?", "")
This is similar to replaceAll, but replaceAll uses a regex.
replace() replaces all occurances in the string.
Now, as to what you did wrong:
When you found a match in the character array, you shift the remaining characters towards the head.
Starting with "abc??def", your first match is at i=3.
You shift all the remaining characters to get "abc?def"
Then, you increment i to 4, and carry on.
c[4] is 'd' at this point.
So, the error is that when you shifted the characters to the left, you still increment i anyway, causing the first shifted character to be skipped.

Related

Java program to find the letter that appears in the most words?

I have a sentence, and I want to find the char that appears in the most words, and how many words it appears in.
For example: "I like visiting my friend Will, who lives in Orlando, Florida."
Which should output I 8.
This is my code:
char maxChar2 = '\0';
int maxCount2 = 1;
for (int j=0; j<strs2.length; j++) {
int charCount = 1;
char localChar = '\0';
for (int k=0; k<strs2[j].length(); k++) {
if (strs2[j].charAt(k) != ' ' && strs2[j].charAt(k) != maxChar2) {
for (int l=k+1; l<strs2[j].length(); l++) {
if (strs2[j].charAt(k)==strs2[j].charAt(l)) {
localChar = strs2[j].charAt(k);
charCount++;
}
}
}
}
if (charCount > maxCount2) {
maxCount2 = charCount;
maxChar2 = localChar;
}
}
, where strs2 is a String array.
My program is giving me O 79. Also, uppercase and lowercase do not matter and avoid all punctuation.
As a tip, try using more meaningful variable names and proper indentation. This will help a lot especially when your program is not doing what you thought it should do. Also starting smaller and writing some tests for it will help a bunch. Instead of a full sentence, get it working for 2 words, then 3 words, then a more elaborate sentence.
Rewriting your code to be a bit more readable:
// Where sentence is: "I like".split(" ");
private static void getMostFrequentLetter(String[] sentence) {
char mostFrequentLetter = '\0';
int mostFrequentLetterCount = 1;
for (String word : sentence) {
int charCount = 1;
char localChar = '\0';
for (int wordIndex = 0; wordIndex < word.length(); wordIndex++) {
char currentLetter = word.charAt(wordIndex);
if (currentLetter != ' ' && currentLetter != mostFrequentLetter) {
for (int l = wordIndex + 1; l < word.length(); l++) {
char nextLetter = word.charAt(l);
if (currentLetter == nextLetter) {
localChar = currentLetter;
charCount++;
}
}
}
}
if (charCount > mostFrequentLetterCount) {
mostFrequentLetterCount = charCount;
mostFrequentLetter = localChar;
}
}
}
Now all I did was rename your variables and change your for loop to a for-each loop. By doing this you can see more clearly your algorithm and what you're trying to do. Basically you're going through each word and comparing the current letter with the next letter to check for duplicates. If I run this with "I like" i should get i 2 but instead I get null char 1. You aren't properly comparing and saving common letters. This isn't giving you the answer, but I hope this makes it more clear what your code is doing so you can fix it.
Here is a somewhat more elegant solution
public static void FindMostPopularCharacter(String input)
{
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
input = input.toUpperCase();
HashMap<Character, Integer> charData = new HashMap<>();
char occursTheMost = 'A'; //start with default most popular char
int maxCount = 0;
//create the map to store counts of all the chars seen
for(int i = 0; i < alphabet.length(); i++)
charData.put(alphabet.charAt(i), 0);
//first find the character to look for
for(int i = 0; i < input.length(); i++)
{
char c = input.charAt(i);
//if contained in our map increment its count
if(charData.containsKey(c))
charData.put(c, charData.get(c) + 1);
//check for a max count and set the values accordingly
if(charData.containsKey(c) && charData.get(c) > maxCount)
{
occursTheMost = c;
maxCount = charData.get(c);
}
}
//final step
//now split it up into words and search which contain our most popular character
String[] words = input.split(" ");
int wordCount = 0;
CharSequence charSequence;
for(Character character : charData.keySet())
{
int tempCount = 0;
charSequence = "" + character;
for(int i = 0; i < words.length; i++)
{
if(words[i].contains(charSequence))
tempCount++;
}
if(tempCount > wordCount)
{
occursTheMost = character;
wordCount = tempCount;
}
}
System.out.println(occursTheMost + " " + wordCount);
}
Output of
String input = "I like visiting my friend Will, who lives in Orlando, Florida.";
FindMostPopularCharacter(input);
is
I 8
Note: If there are ties this will only output the character that first reaches the maximum number of occurrences.
FindMostPopularCharacter("aabb aabb aabb bbaa");
Outputs
B 4
because B reaches the max first before A due to the last word in the input.
FindMostPopularCharacter("aab aab b")
B 3

how to duplicate the characters in between the first and last characters, of a given word?

hey so I'm working on a question that gives me a word and then asks for me to duplicate the letters in between the first and last letters of that word by some number.
I tried to learn how to duplicate the characters through other posts, but I think I'm doing it totally wrong. Can someone help?
this is what I have
public String stretch(String s, int n){
char first = s.charAt(0);
char last = s.charAt(s.length()-1);
String result = "";
for(int i = 1; i < s.length()-2; i++)
for(int j = 0; j < n; j++)
result += first +s.charAt(i)+ last;
return first +result+ last;
public class mainProgram
{
public static void main ( String [ ] args )
{
String word = "example";
String result = stretch ( word , 2 );
System.out.println ( result );
}
public static String stretch(String s, int n){
char first = s.charAt(0);
char last = s.charAt(s.length()-1);
String result = "";
for(int i = 1; i < s.length()-1; i++)
{
for(int j = 0; j < n; j++)
result += s.charAt(i);
}
return first +result+ last;
}
}
You can do it in one line:
return s.replaceAll("(?<!^).(?!$)", new String(new char[n]).replace("\0", "$0"));
Breaking it down:
the find regex matches every char except the first and last (negative look behind and negative look ahead assert this)
the replacement term is n copies of $0, which is the match

Write a program to print each and every alphabet with how many occured in a user input

I have to write a program to accept a String as input, and as output I'll have to print each and every alphabetical letter, and how many times each occurred in the user input. There are some constraints:
I cannot use built-in functions and collection
The printed result should be sorted by occurrence-value.
For example, with this input:
abbbccccdddddzz
I would expect this output:
a-1,z-2,b-3,c-4,d-5
This is what I have so far:
public static void isCountChar(String s) {
char c1[] = s.toCharArray();
int c3[] = new int[26];
for (int i = 0; i < c1.length; i++) {
char c = s.charAt(i);
c3[c - 'a']++;
}
for (int j = 0; j < c3.length; j++) {
if (c3[j] != 0) {
char c = (char) (j + 'a');
System.out.println("character is:" + c + " " + "count is: " + c3[j]);
}
}
}
But I don't know how to sort.
First of all a tip for your next question: The things you've stated in your comments would fit better as an edit to your question. Try to clearly state what the current result is, and what the expected result should be.
That being said, it was an interesting problem, because of the two constraints.
First of all you weren't allowed to use libraries or collections. If this wasn't a constraint I would have suggested a HashMap with character as keys, and int as values, and then the sorting would be easy.
Second constraint was to order by value. Most people here suggested a sorting like BubbleSort which I agree with, but it wouldn't work with your current code because it would sort by alphabetic character instead of output value.
With these two constraints it is probably best to fake key-value pairing yourself by making both an keys-array and values-array, and sort them both at the same time (with something like a BubbleSort-algorithm). Here is the code:
private static final int ALPHABET_SIZE = 26;
public static void isCountChar(String s)
{
// Convert input String to char-array (and uppercase to lowercase)
char[] array = s.toLowerCase().toCharArray();
// Fill the keys-array with the alphabet
char[] keys = new char[ALPHABET_SIZE];
for (int i = 0; i < ALPHABET_SIZE; i++)
{
keys[i] = (char)('a' + i);
}
// Count how much each char occurs in the input String
int[] values = new int[ALPHABET_SIZE];
for (char c : array)
{
values[c - 'a']++;
}
// Sort both the keys and values so the indexes stay the same
bubbleSort(keys, values);
// Print the output:
for (int j = 0; j < ALPHABET_SIZE; j++)
{
if (values[j] != 0)
{
System.out.println("character is: " + keys[j] + "; count is: " + values[j]);
}
}
}
private static void bubbleSort(char[] keys, int[] values)
{
// BUBBLESORT (copied from http://www.java-examples.com/java-bubble-sort-example and modified)
int n = values.length;
for(int i = 0; i < n; i++){
for(int j = 1; j < (n - i); j++){
if(values[j-1] > values[j]){
// Swap the elements:
int tempValue = values[j - 1];
values[j - 1] = values[j];
values[j] = tempValue;
char tempKey = keys[j - 1];
keys[j - 1] = keys[j];
keys[j] = tempKey;
}
}
}
}
Example usage:
public static void main (String[] args) throws java.lang.Exception
{
isCountChar("TestString");
}
Output:
character is: e; count is: 1
character is: g; count is: 1
character is: i; count is: 1
character is: n; count is: 1
character is: r; count is: 1
character is: s; count is: 2
character is: t; count is: 3
Here is a working ideone to see the input and output.
some sort: easy if not easiest to understand an coding
You loop from the first element to the end -1 : element K
compare element K and element K+1: if element K>element K+1, invert them
continue loop
if you made one change redo that !

Print pattern using for loop and return method

I am trying to print
a
bb
ccc
dddd
The code I have is not doing the pattern I would like and not sure where the issue is at. Any help would be great.
public static String generatRowOfSymbols(char letterOne, char letterTwo){
char i;
char j;
String letters = "";
String row = "";
for(i=letterOne; i<= letterTwo; i++ ){
for(j=letterOne; j<=i; j++){
row += i ;
}
letters += row + "\n";
}
return letters;
First, use a StringBuilder -- it's faster and more efficient. I didn't calculate the length, but if you want to, you can. Second, take a look at the changes I made to your method and let me know if it doesn't make sense. Please note that I'm using the System's line separator -- if you really want to append '\n', please do so.
As you should see, our first for-loop walks through the letters. The second, which is nested, prints out count letters, which increments by one each time that we change the letter.
public static String generatRowOfSymbols(char letterOne, char letterTwo) {
StringBuilder letters = new StringBuilder();
int count = 1;
for (char i = letterOne; i <= letterTwo; i++, count++) {
StringBuilder row = new StringBuilder(count);
for (int j = 0; j < count; j++) {
row.append(i);
}
letters.append(row).append(System.lineSeparator());
}
return letters.toString();
}
Edit
Here's yours fixed using Strings instead of StringBuilder, since there is a hesitation to use StringBuilder.
public static String generatRowOfSymbols(char letterOne, char letterTwo) {
String letters = "";
int count = 1;
for (char i = letterOne; i <= letterTwo; i++, count++) {
String row = "";
for (int j = 0; j < count; j++) {
row +=i ;
}
letters += row + System.lineSeparator();
}
return letters;
}
public static String generatRowOfSymbols(char letterOne, char letterTwo){
char i;
char j;
String letters = "";
for(i=letterOne; i<= letterTwo; i++ ){
for(j=letterOne; j<=i; j++){
letters +=i;
}
letters+= "\n";
}
return letters;
The simplest solution that I can come up with is as follows. I used IntStream but you can easily change it to a for-loop; the logic is the same.
public static void printPattern(int rows) {
IntStream.range(0, rows).forEach(x -> {
IntStream.range(0, x + 1).forEach(y -> {
System.out.print((char) ('a' + x));
});
System.out.println();
});
}
Suppose, we use it as follows.
printPattern(10);
Output:
a
bb
ccc
dddd
eeeee
ffffff
ggggggg
hhhhhhhh
iiiiiiiii
jjjjjjjjjj

Java code for finding element for attribute

I am writing a java code for finding element Ex.food for any attribute(attr)Ex.description in XML.
What I have done
I am taking first char of attr as start position and then checking if it equals to "<" .From this point I am looping to ignore white space,tab etc and proceed to append valid char till I find another white space,tab.But this is not working.It is supposed to find the first word after "<" and print that only .But its actually going till the end from the the point it find first char after "<"
Note:I cannot use XML parsers like DOM etc
XML
<breakfast_menu>
<food name="Belgian Waffles" price="$5.95" discount="20"
description="Two" calories="650" />
</breakfast_menu>
for (int k = start_position; k >= 0; k--) {
char testChar = xmlInString.charAt(k);
String temp = Character.toString(testChar);
if ("<".equals(temp)) {
System.out.println(k + "value of k");
for (int j = k + 1; j >= 0; j++) {
char appendChar = xmlInString.charAt(j);
String temp1 = Character.toString(appendChar);
if(!("".equals(temp1))) {
System.out.println(j + " " + appendChar);
}
}
}
}
I made few changes now and its working as expected.i.e giving first word after "<". If you have any suggestion please let me know.
int k, j, l;
for (k = start_position; k >= 0; k--) {
char testChar = xmlInString.charAt(k);
String temp = Character.toString(testChar);
if ("<".equals(temp)) {
break;
}
}
for (j = k + 1; j <= start_position; j++) {
char appendChar = xmlInString.charAt(j);
String temp1 = Character.toString(appendChar);
if (!("".equals(temp1))) {
break;
}
}
for (l = j; l <= start_position; l++) {
char appendChar1 = xmlInString.charAt(l);
String temp2 = Character.toString(appendChar1);
if (" ".equals(temp2)) {
break;
}
}
System.out.println(xmlInString.substring(j, l));
I think this will help
String str = "<food name=\"Belgian Waffles\" price=\"$5.95\" discount=\"20\"\n" ;
String res = str.substring(str.indexOf("<"), str.indexOf(" ", str.indexOf("<") + "<".length()) + " ".length());
System.out.println(res);
output
<food
Your inner while loop for (int j = k + 1; j >= 0; j++) { is broken. The condition j >= 0 doesn't make sense - j only increments so how could it ever be < 0? Instead you should be looking for the next space, tab, etc.
I don't think your solution is going to work, but that is what's wrong with the code you have posted and why it's running off the end.

Categories