Share

Search Java Code Snippets


  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.





#Java - Code Snippets for '#String' - 50 code snippet(s) found

 Sample 1. Write a Program to reverse a string iteratively and recursively

Using String method -

new StringBuffer(str).reverse().toString();

Iterative -

Strategy - Loop through each character of a String from last to first and append the character to StringBuilder / StringBuffer

public static String getReverseString(String str){
StringBuffer strBuffer = new StringBuffer(str.length);
for(int counter=str.length -1 ; counter>=0;counter--){
strBuffer.append(str.charAt(counter));
}
return strBuffer;
}

Recursive -

Strategy - Call the method with substring starting from 2nd character recursively till we have just 1 character.

public static String getReverseString(String str){
if(str.length <= 1){
return str;
}
return (getReverseString(str.subString(1)) + str.charAt(0);
}

   Like      Feedback     string  StringBuffer  recursion  for loop  stringbuffer.append  java.lang.String  java.lang.StringBuffer  String Manipulation


 Sample 2. Tricky code for String Comparison and String Pool

class BuggyBread { 
public static void main(String[] args)
{
String s2 = "I am unique!";
String s5 = "I am unique!";

System.out.println(s2 == s5); // prints true
}
}

   Like      Feedback     tricky code example  string  string comparison  object comparison   object equality   string equality   string pool


 Sample 3. Check if the string is empty using Spring StringUtils

String str = "";
if(StringUtils.isEmpty(str)){
System.out.println("Yes, string is empty");
}

   Like      Feedback     StringUtils  StringUtils.isEmpty


 Sample 4. Concatenate Strings

String str = new String().concat("Explain").concat("This").concat("Code");

   Like      Feedback     string  string concatenation  concat


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 5. Using Pojomatic for overriding equals,hashcode and toString methods

import org.pojomatic.Pojomatic;
import org.pojomatic.annotations.AutoProperty;

@AutoProperty
public class Employee {
   public String name;
   public int age;
   public int salary;

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   public int getAge() {
      return age;
   }

   public void setAge(int age) {
      this.age = age;
   }

   public int getSalary() {
      return salary;
   }

   public void setSalary(int salary) {
      this.salary = salary;
   }

   @Override
   public int hashCode() {
      return Pojomatic.hashCode(this);
   }

   @Override
   public boolean equals(Object other) {
      return Pojomatic.equals(this, other);
   }

   @Override
   public String toString() {
      return Pojomatic.toString(this);
   }
}

   Like      Feedback     pojomatic  toString method  toString  hashcode method  equals method   overrding equals method  overriding hashcode method  overrding tostring method  @autoproperty  pojomatic autoproperty


 Sample 6. Code to find email ids in a string using Pattern.

String text="vivek boy goy vivek@tech.com viv@ek.com sdjs@adjk";
Pattern regex = Pattern.compile("[@]");
Matcher regexMatcher = regex.matcher(text);
int i =0;
int width = 0;
while (regexMatcher.find()) {
if((regexMatcher.start()-10 > 0) && (regexMatcher.end()+10 < text.length())){
width=10;
String[] substr=text.substring(regexMatcher.start()-width,regexMatcher.end()+width).split(" ");
for(int j=0;j<substr.length;j++){
if(substr[j].contains("@") && (substr[j].contains(".com") || substr[j].contains(".net"))){
System.out.println(substr[j]);
}
}
} else {
width=0;
}
}

   Like      Feedback     regex  pattern  string  regexMatcher.find  java.util.regex.Matcher  java.util.regex.Pattern


 Sample 7. Method to check if input String is Palindrome

private static boolean isPalindrome(String str) {
if (str == null)
return false;
StringBuilder strBuilder = new StringBuilder(str);
strBuilder.reverse();
return strBuilder.toString().equals(str);
}

   Like      Feedback     Palindrome   strBuilder.reverse   string  stringbuilder.reverse  java.lang.StringBuilder


 Sample 8. Method that will remove given character from the String

private static String removeChar(String str, char c) {
if (str == null)
return null;
return str.replaceAll(Character.toString(c), "");
}

   Like      Feedback     string  string.replaceall  Character.toString


 Sample 9. Get the content of a file in a string

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileToString {

public static void main(String[] args) throws IOException {

String line = null;

String wholePage = "";

FileReader fileReader =
new FileReader("/home/vivekvermani/test.txt");

BufferedReader bufferedReader =
new BufferedReader(fileReader);

while((line = bufferedReader.readLine()) != null) {
wholePage = wholePage + line + "
";
}

bufferedReader.close();

System.out.println(wholePage);
}
}

   Like      Feedback     reading file to string  import


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 10. Replace all occurrences of a character or substring in a string

String myString = new String("Nevada,Kansas,Georgia");

myString = myString.replaceAll(",", " ");

System.out.println(myString); // prints Nevada Kansas Georgia

   Like      Feedback     string   substring  replaceAll


 Sample 11. Check if a string contains a substring.

String text = "I don't think we're in Kansas anymore";

if(text.indexOf("Kansas") != -1){
System.out.println("Yes, the dialog contains Kansas");
}

   Like      Feedback     string  substring  indexOf()


 Sample 12. Get the subString from a String using the begin and end index

String text = "I don't think we're in Kansas anymore";

// Usage string.substring(startIndex,endIndex)

String subStringText = text.substring(0,2);

System.out.println(subStringText); // prints I d

   Like      Feedback     string  substring  substring using indices


 Sample 13. Trim New line and spaces in a string

String trimNewLineAndSpace(String str){
str = str.trim();
if(str.startsWith("\n")){
str = str.substring(1);
}

if(str.endsWith("\n")){
str = str.substring(0, str.length()-1);
}
return str;
}

   Like      Feedback     string  trim new lines  string.substring  string.startswith  string.endswith


 Sample 14. Trim a String till first capital character.

String trimTillFirstCapitalCharacter(String str){
   for(int i=0;i<str.length();i++){
      if(str.charAt(i) != str.toLowerCase().charAt(i)){
         return str.substring(i);
      }
   }
   return str;
}

   Like      Feedback     trim characters   trim


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 15. Trim square braces and spaces from a String

String trimSquareBracesAndSpaces(String str){
   str = str.trim();
   if(str.startsWith("[")){
      str = str.substring(1);
   }
      
   if(str.endsWith("]")){
      str = str.substring(0, str.length()-1);
   }
   return str;
}

   Like      Feedback     string  string trim   trim


 Sample 16. Remove templatized arguments from a String

String removeTemplatizedArgument(String str){
   String cleanStr = "";
   boolean withinTemplatized=false;   
   int countBlock = 0;
   for(char x: str.toCharArray()){
      if(x == '<'){
         withinTemplatized = true;
         countBlock++;
         continue;
      } else if(x == '>'){
         withinTemplatized = false;
         countBlock--;
         continue;
      } else if(!withinTemplatized && countBlock == 0){
         cleanStr = cleanStr + x;
      }
         
   }
      
   return cleanStr;
}

   Like      Feedback     string  string trim  trim  char  .toCharArray()


 Sample 17. Remove Alien characters i.e removing everything except characters , numbers and special characters.

String removeAlienCharacters(String str){
   String newString = new String();
   String returnString = "";
   if(str.contains("<")){
      String[] str2 = str.split("<");
      str = str2[0];
   }
      
   for(char x: str.toCharArray()){
      if((x >= 48 && x <= 57) || (x>=65 && x <= 90) || (x >= 97 && x<= 122) || x=='.'){
         returnString += x;
      }
   }
   return returnString.trim();
}

   Like      Feedback     string  .contains()  .split()  string split  string contains  remove characters from string  remove alien characters


 Sample 18. Method to convert all elements of a collection ( Set ) to lower case.

Set<String> convertLowerCase(Set<String> set){
   Set<String> newSet = new HashSet();
   for(String s: set){
      newSet.add(s.toLowerCase());
   }
      
   return newSet;
}

   Like      Feedback     string  collections  set  .tolowercase()


 Sample 19. Usage of StringBuffer

StringBuffer strBuffer = new StringBuffer();
strBuffer.append("I don't think");
strBuffer.sppend("we're in Kansas anymore");
String string = strBuffer.toString();

   Like      Feedback     stringbuffer


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 20. Get all words from a String and display them

String string = "I don't think we are in Kansas anymore";
String splittedString = str1.split(" ");
int count = 1;
for(String str: splittedString){
   System.out.println("Word number:" + count + ":" + str);
   count++;
}

   Like      Feedback     string  string split  Get all words from a String   word count


 Sample 21. Method to remove duplicates from a Map ( string and List of objects ) by matching the member field of the object.

Map<String,List<ClassInfoBean>> removeDuplicates(Map<String, List<ClassInfoBean>> interfaceMap){
   Map<String, List<ClassInfoBean>> interfaceMapWithoutDuplicate = new HashMap();
      
   for(Map.Entry<String, List<ClassInfoBean>> entry: interfaceMap.entrySet()){
      List<ClassInfoBean> classListWithoutDuplicate = new ArrayList();
      boolean alreadyContain = false;
      for(ClassInfoBean classes: entry.getValue()){
         for(ClassInfoBean classes1: classListWithoutDuplicate){
            if(classes1.name.equalsIgnoreCase(classes.name)){
               alreadyContain = true;
               break;
            }
         }
         if(alreadyContain == false){
            classListWithoutDuplicate.add(classes);
         }
      }
      interfaceMapWithoutDuplicate.put(entry.getKey(), classListWithoutDuplicate);
   }
      
   return interfaceMapWithoutDuplicate;
}

   Like      Feedback     map  map of list of objects  remove duplicates from map  Map.Entry


 Sample 22. Method to get a map of words and their count by passing in the string

Map<String,Integer> wordCountMap = new TreeMap();
String[] words = text.split(" ");
Set<Integer> countSet;
for(String word: words) {
if(wordCountMap.containsKey(word.toLowerCase())){
wordCountMap.put(word.toLowerCase(), wordCountMap.get(word.toLowerCase()).intValue() + 1);
} else {
wordCountMap.put(word.toLowerCase(), 1);
}
}

countSet = new TreeSet(Collections.reverseOrder());
countSet.addAll(wordCountMap.values());

for(Integer inte: countSet) {
for(Entry<String,Integer> entry: wordCountMap.entrySet()){
if(entry.getValue() == inte) {
System.out.println(entry);
}
}
}

   Like      Feedback     map  word count  map of string and integer  containsKey  string split  treeset  Collections.reverseOrder  set addAll   entry


 Sample 23. Initialize Date using SimpleDateFormat and parsing string

Date endDate = new SimpleDateFormat("yyyyMMdd").parse("20160426");

   Like      Feedback     SimpleDateFormat   Date   SimpleDateFormat.parse  java.text.SimpleDateFormat


 Sample 24. Null or Empty String check using string length

String str= "";

if (str != null || str.length() != 0) {
   // Do something
}

   Like      Feedback     string  null check   String.length  check empty string


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 25. Find shortest and longest word in a string

public static void main(String[] args) {
String str = "We are not in Kansas anymore";
String shortestWord = "";
String longestWord = "";
int shortestWordLength = 1000;
int longestWordLength = 0;
String[] splitStr = str.split(" ");
for(String string: splitStr){
if(string.length() > longestWordLength){
longestWord = string;
longestWordLength = string.length();
} else if(string.length() < shortestWordLength){
shortestWord = string;
shortestWordLength = string.length();
}
}

System.out.println("Shortest Word :" + shortestWord);
System.out.println("Longest Word :" + longestWord);
}

   Like      Feedback     string  string.split


 Sample 26. Write a Program to print ascii value of each character of a string

public static void main(String[] args) {
String str = "We are not in Kansas anymore";
for(char character: str.toCharArray()){
System.out.println((int)character);
}
}

   Like      Feedback     ascii  character


 Sample 27. Copy Array using System.arraycopy

String[] stringArray = new String[50];
String[] newStringArray = new String[50];
System.arraycopy(stringArray, 0, newStringArray, 0, 50); //arrayCopy(src,srcPosition,destination,destinationPos,length)

   Like      Feedback     System.arraycopy  Copy array  arrays  array of string


 Sample 28. Repeat a string using Google Guava Strings Class

System.out.println(Strings.repeat("Hello", 5));

   Like      Feedback     google guava  google guava string  strings.repeat  repeat characters   repeat string


 Sample 29. Convert int to String

int x = 5;
String.valueOf(x);

   Like      Feedback     String  String.valueOf  int to String


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 30. Usage of Apache Commons CharSet

String str = new String("Hello World");
CharSet charSet = CharSet.getInstance(str);
System.out.println(charSet.contains('W')); // prints true
System.out.println(charSet.contains('w')); // prints false

   Like      Feedback     CharSet  Apache Commons  CharSet Example  CharSet Sample  String  characters


 Sample 31. Remove characters from the String using CharSetUtils

String str = new String("Hello World"); 
String newStr = CharSetUtils.delete(str, "abcde");
System.out.println(newStr); // prints Hllo Worl

   Like      Feedback     Remove characters from the String  String  CharSetUtils  Apache Commons


 Sample 32. Remove Numbers from a String using CharSetUtils (Apache Commons)

String str = new String("1H4ello1 World2"); 

String newStr = CharSetUtils.delete(str, "1234567890");

System.out.println(newStr); // prints Hello World

   Like      Feedback     Apache Commons  CharSetUtils   Remove Numbers from String


 Sample 33. Remove special characters from a String using CharSetUtils ( Apache Commons )

String str = new String("What's Up ?"); 

String newStr = CharSetUtils.delete(str, "'?");

System.out.println(newStr); // prints Whats Up

   Like      Feedback     Apache Commons  CharSetUtils  Remove characters from String


 Sample 34. Check if the String contains specified characters using CharSetUtils (Apache Commons)

System.out.println(CharSetUtils.containsAny("Whats Up ?", "W")); // Prints true as the String contains character W  System.out.println(CharSetUtils.containsAny("Whats Up ?", "YZ")); // Prints false as the String doesn't contain character Y or Z

   Like      Feedback     CharSetUtils (Apache Commons)  Check if String contains characters


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 35. Print the characters that exist in the specified String using CharSetUtils ( Apache Commons )

System.out.println(CharSetUtils.keep("Whats Up ?", "Watch")); // Prints Wat as only those characters matches in the String 

   Like      Feedback     Characters that exist in String  CharSetUtils ( Apache Commons )


 Sample 36. Get Length of String having UTF8 Characters

public static int utf8Length(String string) {
   CharacterIterator iter = new StringCharacterIterator(string);
   char ch = iter.first();
   int size = 0;
   while (ch != CharacterIterator.DONE) {
      if ((ch >= 0xD800) && (ch < 0xDC00)) {
         char trail = iter.next();
         if ((trail > 0xDBFF) && (trail < 0xE000)) {
            size += 4;
         } else {
            size += 3;
            iter.previous(); // rewind one
         }
      } else if (ch < 0x80) {
         size++;
      } else if (ch < 0x800) {
         size += 2;
      } else {
         size += 3;
      }
      ch = iter.next();
   }
   return size;
}

   Like      Feedback     UTF8 characters  CharacterIterator.DONE  CharacterIterator  StringCharacterIterator


 Sample 37. Count Occurences of substring in a String using StringUtils ( Apache Commons )

if(StringUtils.countMatches(snippet, "{") == StringUtils.countMatches(snippet, "}")){
         System.out.println("Yes a Valid Code Snippet");
      }

   Like      Feedback     StringUtils  Apache Commons  Count Occurences of substring


 Sample 38. Code Sample / Example / Snippet of java.util.StringTokenizer

  public static List<String> getNamedOutputsList(JobConf conf) {

List<String> names = new ArrayList<String>();

StringTokenizer st = new StringTokenizer(conf.get(NAMED_OUTPUTS, ""), " ");

while (st.hasMoreTokens()) {

names.add(st.nextToken());

}

return names;

}


   Like      Feedback      java.util.StringTokenizer


 Sample 39. Code Sample / Example / Snippet of java.io.StringWriter

  public Fluent returns(Function<String, Void> checker) throws ParseException {

final Ast.Program program = parseProgram(pig);

final PigRelBuilder builder =

PigRelBuilder.create(PigRelBuilderTest.config().build());

final StringWriter sw = new StringWriter();

new CalciteHandler(builder, sw).handle(program);

checker.apply(Util.toLinux(sw.toString()));

return this;

}


   Like      Feedback      java.io.StringWriter


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 40. Code Sample / Example / Snippet of java.util.StringTokenizer

    private List<String> tokenize(String s) {

List<String> result = new ArrayList<>();

StringTokenizer tokenizer = new StringTokenizer(s);

while (tokenizer.hasMoreTokens()) {

result.add(tokenizer.nextToken());

}

return result;

}


   Like      Feedback      java.util.StringTokenizer


 Sample 41. Code Sample / Example / Snippet of org.apache.calcite.avatica.util.ByteString

  private void thereAndBack(byte[] bytes) {

final ByteString byteString = new ByteString(bytes);

final byte[] bytes2 = byteString.getBytes();

assertThat(bytes, equalTo(bytes2));



final String base64String = byteString.toBase64String();

final ByteString byteString1 = ByteString.ofBase64(base64String);

assertThat(byteString, equalTo(byteString1));

}


   Like      Feedback      org.apache.calcite.avatica.util.ByteString


 Sample 42. Given a Map with Country Name as key and its capitals as values, Find the name of countries having more than 1 capital ?

Map<String,List<String>> capitals = new HashMap();
capitals.put("United States", Arrays.asList("Washington DC"));
capitals.put("Canada", Arrays.asList("Ottawa"));
capitals.put("South Africa", Arrays.asList("Pretoria", "Cape Down", "Bloemfontein"));
      
for(Map.Entry<String,List<String>> entry: capitals.entrySet()){
   if(entry.getValue().size() > 1){
      System.out.println(entry.getKey());
   }
}

   Like      Feedback     Map of String and List


 Sample 43. Code Sample / Example / Snippet of java.text.StringCharacterIterator

    public static String encode(String source) {

if (source == null) {

return "$e";

}

StringBuffer result = new StringBuffer();

StringCharacterIterator sci = new StringCharacterIterator(source);

for (char c = sci.current(); c != CharacterIterator.DONE; c = sci.next()) {

if (c == '$') {

result.append("$$");

}

else if (c == ',') {

result.append("$k");

}

else if (c == ' ') {

result.append("$n");

}

else if (c == ' ') {

result.append("$r");

}

else {

result.append(c);

}

}

return result.toString();

}


   Like      Feedback      java.text.StringCharacterIterator


 Sample 44. Code Sample / Example / Snippet of java.util.StringTokenizer

	public LowestID(String representation) {

try {

StringTokenizer st = new StringTokenizer(representation, ",");

m_targetID = Codec.decode(st.nextToken());

m_storeID = Long.parseLong(st.nextToken());

m_lowestID = Long.parseLong(st.nextToken());

}

catch (NoSuchElementException e) {

throw new IllegalArgumentException("Could not create lowest ID object from: " + representation);

}

}


   Like      Feedback      java.util.StringTokenizer


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 45. Code Sample / Example / Snippet of org.apache.bcel.classfile.ConstantString

    public String stringifyValue()

{

final ConstantUtf8 cu8 = (ConstantUtf8) getConstantPool().getConstant(valueIdx);

return cu8.getBytes();

}


   Like      Feedback      org.apache.bcel.classfile.ConstantString


 Sample 46. Write CSV values to a file using au.com.bytecode.opencsv.CSVWriter

String[] stringArray1 = new String[5];
String[] stringArray2 = new String[5];
String[] stringArray3 = new String[5];

List listOfStringArrays = new ArrayList();
listOfStringArrays.add(stringArray1);
listOfStringArrays.add(stringArray2);
listOfStringArrays.add(stringArray3);

File file = new File("BuggyBread.txt");
CSVWriter csvWriter = null;
try {
   csvWriter = new CSVWriter(new FileWriter(file),CSVWriter.DEFAULT_SEPARATOR);
} catch (Exception ex){
}
csvWriter.writeAll(listOfStringArrays);

   Like      Feedback     array of Strings  csv writer


 Sample 47. Write a program / method to print first letter of words in a string.

public void printFirstLetterOfWords(String str){
   String[] splittedStringArray = str.split(" ");
   for(String word:splittedStringArray){
      System.out.println(word.charAt(0));
   }
}

   Like      Feedback     Code  Coding  String


 Sample 48. Print duplicate characters in a string / char array without using library

public class CountDuplicates {
   public static void main(String[] args){
      char[] alreadyOccured = new char[10];
      
      char[] charArray = {'b','u','g','g','y','b','r','e','a','d'};
      
      for(int countArray=0;countArray<charArray.length;countArray++){
         boolean charAlreadyOccured = false;
         for(int countAlreadyOccured=0;countAlreadyOccured<alreadyOccured.length;countAlreadyOccured++){
            if(charArray[countArray] == alreadyOccured[countAlreadyOccured]){
               charAlreadyOccured = true;
               break;
            }
         }
         if(charAlreadyOccured){
            System.out.println(charArray[countArray]);
         } else {
            alreadyOccured[countArray] = charArray[countArray];
         }
      }
   }
}

   Like      Feedback     string  char array


 Sample 49. Write a Program to replace characters in a String ( without using String replace method )

public class ReplaceCharacters{
   public static void main(String[] args){
      String str = "Hello BuggyBread";
      
      char[] charArray = str.toCharArray();
      int countCharacter = str.length();
      for(int count=0;count<countCharacter;count++){
         if(charArray[count] == 'g'){
            charArray[count] = 'd';
         }
      }
      String replacedString = new String(charArray).toString();
      
      System.out.println(replacedString);
   }
}

   Like      Feedback     string  replace characters in a string


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 50. Write a Program to right shift single character in a string

public class RightShiftCharacter {
   public static void main(String args[]) {
      String str = "Hello";
      
      char[] charArray = str.toCharArray();
      
      for(int count=charArray.length-1;count>0;count--){
         charArray[count] = charArray[count-1];
      }
      
      String newString = new StringBuilder().append(charArray).toString();
      
      System.out.println(newString);      
   }
}

   Like      Feedback     string manipulation.right shift character



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner



comments powered by Disqus