public class Test {
public static void main(String[] args) {
String str = "My CID is #encode2#123456789#encode2# I am from India";
String[] tokens = str.split("#encode2#");
for (int i = 0; i < tokens.length; i++) {
// prints the tokens
System.out.println(tokens[i]);
}
}
}
Output will be
My CID is
123456789
I am from India
But I want only 123456789 from this whole String and I want to use that 123456789 number for encryption.
I also use if(!"#encode2#".equals(text)) condition but still not getting output.
How to write condition like need strat from #encode2# right part and end before #encode2#.
Use String's indexOf and lastIndexOf methods to find the index where the two #encode2# substrings start. Then, use substring to get the string between those two indices.
String str = "My CID is #encode2#123456789#encode2# I am from India";
String substring = "#encode2#";
int firstIdx = str.indexOf(substring);
int secondIdx = str.lastIndexOf(substring);
System.out.println(str.substring(firstIdx + substring.length(), secondIdx)); //123456789
public String getToken() {
String str = "My CID is #encode2#123456789#encode2# I am from India";
int start = str.indexOf("#encode2#") + "#encode2#".length();
int end = str.lastIndexOf("#encode2#");
return str.substring(start, end);
}
Note: This method only works if you have "#encode2#" twice in your String value. If you there are multiple instances of the Token you need, this doesn't work.
Related
I am creating a CamelCase function in Java that takes a string this_is_a_sentence and returns ThisIsASentence My main problem comes with handeling the different characters in the string.
So far I have:
import java.util.Scanner;
public class Main{
public static String camelCaser(String str){
char[] strChr = str.toCharArray();
strChr[0] = strChr[0].toUpperCase;
for(int i = 0; i < strChr.length; i++){
if (strChr[i] == '_'){
strChr[i] = strChr[i+1].toUpperCase;
strChr[i+1] = "";
}
}
String newStr = new String(strChr);
return newStr;
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("String: ");
String str = input.next();
System.out.printf("Converting: %s into %s", str, camelCaser(str));
}
}
My main problems seems to be that you can not alter individual characters the same way that I am used to in C. I have read that you can use a class called Character but I cant figure out how to use it. The Java documentation on the matter https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html did not help me either.
I changed around a bit of your logic to make this work. The easiest thing to make it work was to search the string for _, and then capitalize the following letter. After that, take the resulting string and remove all the _'s. It ended up like this:
import java.util.Scanner;
public class Caser{
public static String camelCaser(String str){
char[] strChr = str.toCharArray();
strChr[0] = Character.toUpperCase(strChr[0]);
for(int i = 0; i < strChr.length; i++) if (strChr[i] == '_') strChr[i+1] = Character.toUpperCase(strChr[i+1]);
String reply = new String(strChr);
reply = reply.replace("_", "");
return reply;
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("String: ");
String str = input.next();
System.out.printf("Converting: %s into %s", str, camelCaser(str));
}
}
EDIT:
What does String reply = new String(strChr); do?
This creates a new variable named reply. The variable is a String. new String(strChr) is a helper that the String class has whereby you can give it a char[] and it will automatically turn it into a String.
What does reply = reply.replace("_", ""); do?
.replace(String, String) is a String method that will search said string (in this case, reply) and will search for all instances of _ and when it finds them it will replace it with an empty String (in this case, it is blank "").
This code has several problems. First, toUpperCase() cannot be used on a char, you'd need to call Character.toUpperCase(character). Second, strChar[i+1]=""; does not compile, as "" is the empty String, strChar is a array of char.
I'd do something like this: first, I would split the string by "_" if you're sure you only want this as your separating character using String[] words = str.split("_"). Then, I would create a new String which will be the result String (let's call it res). After that, I would loop over all elements in words, make the first character upper case, add it to res and add all the other characters of the current element to res.
So, it would look like this:
public static String camelCaser(String str){
String[] words = str.split("_"); // split str by _
String res = ""; // result string
for(String word : words) {
// first check, if words is empty
if(!word.isEmpty()) {
// add first character upper case
res += Character.toUpperCase(word.charAt(0));
// add remaining characters as they are, if any
if(word.length() > 1) {
res += word.substring(1);
}
}
}
return res;
}
You would need to do something like Character.toUpperCase(strChr[0]); to convert a character in your array to uppercase.
Use Character.toUpperCase(char).
public class Main{
public static String camelCaser(String str){
char[] strChr = str.toCharArray();
strChr[0] = Character.toUpperCase(strChr[0]);
for(int i = 0; i < strChr.length; i++){
if (strChr[i] == '_'){
strChr[i] = Character.toUpperCase(strChr[i+1]);
strChr[i+1] = Character.valueOf('\u0000') ;
}
}
String newStr = new String(strChr);
return newStr;
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("String: ");
String str = input.next();
System.out.printf("Converting: %s into %s", str, camelCaser(str));
}
}
I have a string which contains 80+ characters and I want to divide it into two substrings. The first one to contain the first 80 characters and the other one the next characters.
I was able to obtain the first String.
public static void SetStrings(String stringName) {
int numOfChars = stringName.length();
String firstString = stringName.substring(0, 80);
int maxChars = 80;
if (numOfChars > maxChars) {
stringName = firstString;
} else {
stringName = stringName;
}
}
Use this:
String secondString = stringName.substring(80);
You should also look at the Javadoc for String.substring(int).
I want to remove certain characters at specific positions of the String. I have the positions, but I am facing problems removing the characters.
what i am doing is:
if (string.subSequence(k, k + 4).equals("\n\t\t\t")){
string = string.subSequence(0, k) + "" + s.subSequence(k, s.length());
}
I need to remove "\n\t\t\t" from string
Use StringBuilder:
StringBuilder sb = new StringBuilder(str);
sb.delete(start, end);
sb.deleteCharAt(index);
String result = sb.toString();
Use StringBuilder
String str=" ab a acd";
StringBuilder sb = new StringBuilder(str);
sb.delete(0,3);
sb.deleteCharAt(0);
String result = sb.toString();
System.out.println(result);
public static String remove(int postion, String stringName) {
char [] charArray = stringName.toCharArray();
char [] resultArray = new char[charArray.length];
int count = 0;
for (int i=0; i< charArray.length; i++) {
if (i != postion-1) {
resultArray[count] = charArray[i];
count++;
}
}
return String.valueOf(resultArray);
}
Use String.ReplaceAll() instead of this.
But if you only want to remove specific element only you can use substring().
Now you want to know position which you already know.
Put your points in a HashSet called set
StringBuilder sb=new StringBuilder();
for(int i=0;i<string.length();i++){
if(!set.contains(string.charAt(i)))
sb.append(string.charAt(i));
}
String reformattedString=sb.toString();
First you have to put \ in front of the special characters in order to do the matching of the two string, thus you will have .equals("\"\\n\\t\\t\\t\""), otherwise the substring is not going to be recognized inside the string. Then the other thing which you have to fix is the position of the index begin and end inside .subSequence(k,k+10) since the first and the last character are 10 positions apart and not 4. Note also that when you patch the string you go from position 0 to k and from k+10 to str.length(). If you go from 0 --> k and k --> length() you just join the old string together :).
Your code should work like this, I have tested it already
if(str.substring(k, k+10).equals("\"\\n\\t\\t\\t\""))
{
newstr = str.substring(0,k)+str.substring(k+10,(str.length()));
}
also you don't need +" "+ since you are adding strings. Whoever wants to see the effect of this can run this simple code:
public class ReplaceChars_20354310_part2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String str = "This is a weird string containg balndbfhr frfrf br brbfbrf b\"\\n\\t\\t\\t\"";
System.out.println(str); //print str
System.out.println(ReplaceChars(str)); //then print after you replace the substring
System.out.println("\n"); //skip line
String str2 = "Whatever\"\\n\\t\\t\\t\"you want to put here"; //print str
System.out.println(str2); //then print after you replace the substring
System.out.println(ReplaceChars(str2));
}
//Method ReplaceChars
public static String ReplaceChars (String str) {
String newstr ="";
int k;
k = str.indexOf("\"\\n\\t\\t\\t\""); //position were the string starts within the larger string
if(str.substring(k, k+10).equals("\"\\n\\t\\t\\t\""))
{
newstr = str.substring(0,k)+str.substring(k+10,(str.length())); //or just str
}
return newstr;
}//end method
}
I have a string in java, of uncertain length, and I need to take the first 3 and last 3 characters and put them into new strings. Is there a simple way to do this?
Funny, all solutions are buggy (update: except the one with the regex) and may result in StringIndexOutOfBoundsException when the input string's length is less then 3 (the question explicitly says the length is uncertain). Assuming that str is not null, the proper way would be:
String first = str.substring(0, Math.min(str.length(), 3));
String second = str.substring(Math.max(0, str.length() - 3), str.length());
You could use the substring method:
String text = "Hello world!";
String newText = text.substring(0, 3) + text.substring(text.length-3);
This will take "Hello world!" and create a new string which is "Helld!".
If you are looking for a method that you can use:
String trimThreeCharacters(text){
return text.substring(0,3) + text.substring(text.length-3);
}
str.substring(0, 3) + str.substring(str.length - 3)
EDIT:
This code is not safe. I leave it for you to check whether string is not too short.
You can also use regular expressions:
Pattern p = Pattern.compile("^(.{3}).*(.{3})$");
Matcher m = p.matcher(str);
if (m.find()) {
String s1 = m.group(1);
String s2 = m.group(2);
}
Refer to documentation
public class Substring {
public static void main(String[] args) {
String input = "very long string, with random content";
System.out.println(input.substring(0, 3));
int length = input.length();
System.out.println(input.substring(length - 3));
}
}
Result
ver
ent
Another way of doing this
public class MyString
{
private String value;
public MyString(String p_value)
{
value = p_value;
}
public String getFirstThree()
{
return value.substring(0, 3);
}
public String getLastThree()
{
return value.substring(value.length() - 3);
}
public String getNewString()
{
return getFirstThree() + getLastThree();
}
public static void main(String[] args)
{
MyString example = new MyString("hello world");
String newString = example.getNewString();
System.out.println(newString);
}
}
new_string = old_string.substring(0,3) +
old_string.substring(old_string.lenght() - 3)
As milan already said, substring is the way to go here. You can see some examples of use here.
String FullName = "Cande Nauer";
String FirstNameChars = "";
FirstNameChars = FullName.substring( 0, 3 );
In this example, FirstNameChars will be "Can". To get the last three characters you will have to obtain the length og the string first.
I'm trying to create a palindrome tester program for my AP Java class and I need to remove the white spaces in my code completely but it's not letting me do so.
import java.util.Scanner;
public class Palin{
public static boolean isPalindrome(String stringToTest) {
String workingCopy = removeJunk(stringToTest);
String reversedCopy = reverse(workingCopy);
return reversedCopy.equalsIgnoreCase(workingCopy);
}
public static String removeJunk(String string) {
int i, len = string.length();
StringBuffer dest = new StringBuffer(len);
char c;
for (i = (len - 1); i >= 0; i-=1) {
c = string.charAt(i);
if (Character.isLetterOrDigit(c))
{
dest.append(c);
}
}
return dest.toString();
}
public static String reverse(String string) {
StringBuffer sb = new StringBuffer(string);
return sb.reverse().toString();
}
public static void main(String[] args) {
System.out.print("Enter Palindrome: ");
Scanner sc = new Scanner(System.in);
String string = sc.next();
String str = string;
String space = "";
String result = str.replaceAll("\\W", space);
System.out.println(result);
System.out.println();
System.out.println("Testing palindrome:");
System.out.println(" " + string);
System.out.println();
if (isPalindrome(result)) {
System.out.println("It's a palindrome!");
} else {
System.out.println("Not a palindrome!");
}
System.out.println();
}
}
Any help would be greatly appreciated.
Seems like your code is fine except for the following. You are using
String string = sc.next();
which will not read the whole line of input, hence you will lose part of the text. I think you should use the following instead of that line.
String string = sc.nextLine();
If you just want to remove the beginning and ending whitespace, you can use the built in function trim(), e.g. " abcd ".trim() is "abcd"
If you want to remove it everywhere, you can use the replaceAll() method with the whitespace class as the parameter, e.g. " abcd ".replaceAll("\W","").
Use a StringTokenizer to remove " "
StringTokenizer st = new StringTokenizer(string," ",false);
String t="";
while (st.hasMoreElements()) t += st.nextElement();
String result = t;
System.out.println(result);
I haven't actually tesed this, but have you considered the String.replaceAll(String regex, String replacement) method?
public static String removeJunk (String string) {
return string.replaceAll (" ", "");
}
Another thing to look out for is that while removing all non-digit/alpha characters removeJunk also reverses the string (it starts from the end and then appends one character at a time).
So after reversing it again (in reverse) you are left with the original and it will always claim that the given string is a palindrome.
You should use the String replace(char oldChar, char newChar) method.
Although the name suggests that only the first occurrence will be replaced, fact is that all occurrences will be replaced. The advantage of this method is that it won't use regular expressions, thus is more efficient.
So give a try to string.replace(' ', '');