Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

replacing a word in a string - Java

  • 26-03-2015 12:35pm
    #1
    Registered Users Posts: 1,454 ✭✭✭


    Hi there,

    I have an issue I need help with.

    I want the user to enter a string and if the string contains particular words I want them to be swapped for another word.

    Example:

    String input "I would like to cu next week xxx"

    String output "I would like to see you next week"

    I have three arrays made:
    1. one for all the words in the string.
    2. one that is a library of acroynms (cu, xxx etc)
    3. one that is translations (see you, kisses etc )

    I have tried using for loops and if statements with little success.
    I then tried converting arrays to lists and iterating each word but that also did not work out.

    Fairly stuck now.

    Any help would be great,

    Boggy.


Comments

  • Registered Users Posts: 403 ✭✭counterpointaud


    Maybe try using some sort of key-value (i.e. Map) data structure for the dictionary of acronyms, instead of an array. Then you can iterate through the array of words and for each word, see if your map contains a key of that word. If so, replace it with the value.


  • Registered Users Posts: 1,454 ✭✭✭bogwalrus


    I will have a look into that. I have tried iterating already but it would not loop properly translating all acronyms. Below is a basic loop where I was trying to remove all detected acronyms from string but that too was not really working.

    [SIZE="2"]Iterator<String> itW = listWords.iterator();
    		Iterator<String> itA = listAcroynms.iterator();
    		Iterator<String> itT = listTrans.iterator();
    			
    			while(itA.hasNext()){
    			
    				if(listWords.contains(itA.next())){
    				
    					itA.remove();
    				
    				   }
    			}
    			
    			for(int i=0; i<listWords.size(); i++ ){
    				
    					System.out.printf("%s", listWords.get(i));
    			
    			}[/SIZE]
    


  • Registered Users Posts: 306 ✭✭yes there


    You do not need to iterate at all. If it contains a key, get the value. So keys can be acronyms and values full form. Read each word, check if map contains it and then replace that word in the output (a new list )with value in map or original word.


  • Registered Users Posts: 403 ✭✭counterpointaud


    Try this:
                    String input = "I would like to cu next week xxx";
    		
    		HashMap<String, String> acronymMap = new HashMap<String, String>();
                    acronymMap.put("cu", "see you");
    	 	
    		String[] words = input.split("\\s+");
    		for (int i = 0; i < words.length; i++) {
    			if(acronymMap.containsKey(words[i])){
    				words[i] = acronymMap.get(words[i]);
    			}
    		}
    		
    		String output = String.join(" ", words);
    		System.out.print(output);
    


  • Closed Accounts Posts: 19,777 ✭✭✭✭The Corinthian


    Why have you split your string into an array of words? Is this a college assignment?


  • Advertisement
  • Registered Users Posts: 1,454 ✭✭✭bogwalrus


    Why have you split your string into an array of words? Is this a college assignment?


    I thought by putting the words in an array it would be the only way I could loop and replace acronyms with the translations. I had tired using
    .contains
    
    with the string.

    Regarding if this is a college assignment, well I am studying soft dev and doing a number of assignments but this particular query stems from a tutorial that i could not figure out.

    I find with java if you hit a wall you need someone to show you a new approach.


  • Moderators, Technology & Internet Moderators Posts: 1,333 Mod ✭✭✭✭croo


    What's wrong with the simple String.replace or maybe even String.replaceAll


  • Moderators, Computer Games Moderators, Technology & Internet Moderators Posts: 19,240 Mod ✭✭✭✭L.Jenkins


    I presume that you know what you need to replace, so I would go with Croos' suggestion.


  • Registered Users Posts: 1,454 ✭✭✭bogwalrus


    croo wrote: »
    What's wrong with the simple String.replace or maybe even String.replaceAll

    I tried that also but it would not work. Maybe a problem with my loop? see code below?
    for(int i=0; i<acroynms.length; i++){
    			
    			if(words[i].contains(acroynms[i])){
    				
    				words[i]=words[i].replaceAll(acroynms[i], translations[i]);
    			}
    			System.out.println(words[i]);
    		}
    

    I also get an NPE error when trying this. I imported all necessary bits but maybe I need to pass something else into the method to get this working?


  • Registered Users Posts: 1,148 ✭✭✭punk_one82


    bogwalrus wrote: »
    I tried that also but it would not work. Maybe a problem with my loop? see code below?
    for(int i=0; i<acroynms.length; i++){
    			
    			if(words[i].contains(acroynms[i])){
    				
    				words[i]=words[i].replaceAll(acroynms[i], translations[i]);
    			}
    			System.out.println(words[i]);
    		}
    

    I also get an NPE error when trying this. I imported all necessary bits but maybe I need to pass something else into the method to get this working?

    You want to be using String.contains and String.replace on the entire string, not individual elements from the array. Using those methods negates the need for splitting your input string into an array in the first place.

    In some basic pseudocode:
    if(inputString.contains(txtSpk)){
        newString = inputString.replace(txtSpk, realWord)
    }
    


    To give you a little bit more info, adding to what others have said. Store the words you want to be replaced(key) and their replacements(value) in a map.

    Loop through the keySet of the map using a for loop, and then use the above pseudocode to do your replacement. Hope this helps a bit.


  • Advertisement
  • Registered Users Posts: 403 ✭✭counterpointaud


    EDIT: What if OP has a large HashMap of txtspeak translations though? He/she is still going to have to check every word against every key in the HashMap. String.contains might not be best solution here.


  • Registered Users Posts: 243 ✭✭Decos


    OP here's a basic parallel arrays technique that will work.
    import java.util.Scanner;
    
    public class ReplaceWords
    {
        public static void main(String [] args)
        {
            Scanner keyboard = new Scanner(System.in);
            System.out.print("Enter a sentence: ");
            String sentence = keyboard.nextLine();
            String[] acronyms = {"cu", "xxx", "lol", "omg"};
            String[] translations = {"see you", "kisses", "laughing out loud", "oh my god"};
            for(int i = 0; i < acronyms.length; i++)
            {
                if (sentence.contains(acronyms[i]))
                {
                    sentence = sentence.replaceAll(acronyms[i], translations[i]);
                }
            }
            System.out.println("The translated sentence is: " + sentence);
        }
    }
    


  • Moderators, Technology & Internet Moderators Posts: 1,333 Mod ✭✭✭✭croo


    Decos wrote: »
    OP here's a basic parallel arrays technique that will work.
    import java.util.Scanner;
    
    public class ReplaceWords
    {
        public static void main(String [] args)
        {
            Scanner keyboard = new Scanner(System.in);
            System.out.print("Enter a sentence: ");
            String sentence = keyboard.nextLine();
            String[] acronyms = {"cu", "xxx", "lol", "omg"};
            String[] translations = {"see you", "kisses", "laughing out loud", "oh my god"};
            for(int i = 0; i < acronyms.length; i++)
            {
                if (sentence.contains(acronyms[i]))
                {
                    sentence = sentence.replaceAll(acronyms[i], translations[i]);
                }
            }
            System.out.println("The translated sentence is: " + sentence);
        }
    }
    
    I guess you'd need to be including spaces in the acronyms otherwise you'd risk replacing the combinations within other words!


  • Registered Users Posts: 243 ✭✭Decos


    croo wrote: »
    I guess you'd need to be including spaces in the acronyms otherwise you'd risk replacing the combinations within other words!

    Indeed!


  • Registered Users Posts: 1,454 ✭✭✭bogwalrus


    I really appreciate all the help. I tried them all but found issues with some. Probably my own fault.

    I eventually started from scratch and used the advice from earlier to stick with replaceAll.

    I eventually got code that does what I want. noOfData is a new int that counts how many bits of data are in my array rather than the whole array. This is what was giving me the Null errors.

    Cheers again.
    for(int j=0; j < noOfData; j++){
    			
    			if(lineOfText.contains(acroynms[j])){
    				
    				transText = lineOfText.replaceAll(acroynms[j], translations[j]);
    				lineOfText = transText;
    			}
    		}
    		System.out.println(transText);
    		
    


  • Registered Users Posts: 1,454 ✭✭✭bogwalrus


    Decos wrote: »
    OP here's a basic parallel arrays technique that will work.
    import java.util.Scanner;
    
    public class ReplaceWords
    {
        public static void main(String [] args)
        {
            Scanner keyboard = new Scanner(System.in);
            System.out.print("Enter a sentence: ");
            String sentence = keyboard.nextLine();
            String[] acronyms = {"cu", "xxx", "lol", "omg"};
            String[] translations = {"see you", "kisses", "laughing out loud", "oh my god"};
            for(int i = 0; i < acronyms.length; i++)
            {
                if (sentence.contains(acronyms[i]))
                {
                    sentence = sentence.replaceAll(acronyms[i], translations[i]);
                }
            }
            System.out.println("The translated sentence is: " + sentence);
        }
    }
    


    Yeah this is pretty much what I did. the only issue was that my arrays had a max length of 100 so I was getting a null error when using array.length even though the code was actually fine.

    A lesson learned anyway. Cheers!


  • Closed Accounts Posts: 768 ✭✭✭SpaceSasqwatch


    I done a txt spk translator as android app.

    Used a hashmap as suggested above and used regex to break the string down into tokens.

    And yes I did put load of words and their proper english translation into the hashmap.Was a major pain in the hole tbh :pac:

    Can pm you my github page if you want so you can have a look.Dont wanna post it here as it has my RL name:pac:


  • Closed Accounts Posts: 19,777 ✭✭✭✭The Corinthian


    I done a txt spk translator as android app.
    What language did you translate to?


  • Closed Accounts Posts: 768 ✭✭✭SpaceSasqwatch


    What language did you translate to?

    from english to txtspk and txtspk to english.

    Was first time using regex so was hard.Had planned adding a database so users
    coukld save their own words as it was nearly impossible to get every possible version of a word(factoring peoples sh1te spelling :) ) but lost my google dev key so never got around to it.

    EDIT:I saw wat ye done there :)


  • Closed Accounts Posts: 768 ✭✭✭SpaceSasqwatch


    What language did you translate to?

    lol just noticed the bold part :o


  • Advertisement
Advertisement