If String a = "abbc" and String b="abc", we have to print that character 'b' is missing in the second string.
I want to do it by using Java. I am able to do it when String 2 has a character not present in String 1 when s1=abc and s2=abk but not when characters are same in both strings like the one I have mentioned in the question.
public class Program
{
public static void main(String[] args) {
String str1 = "abbc";
String str2 = "abc";
char first[] = str1.toCharArray();
char second[] = str2.toCharArray();
HashMap <Character, Integer> map1 = new HashMap<Character,Integer>();
for(char a: first){
if(!map1.containsKey(a)){
map1.put(a,1);
}else{
map1.put(a,map1.get(a)+1);
}
}
System.out.println(map1);
HashMap <Character, Integer> map2 = new HashMap<Character,Integer>();
for(char b: second){
if(!map2.containsKey(b)){
map2.put(b,1);
}else{
map2.put(b,map2.get(b)+1);
}
}
System.out.println(map2);
}
}
I have two hashmaps here one for the longer string and one for the shorter string, map1 {a=1,b=2,c=1} and map2 {a=1,b=1,c=1}. What should I do after this?
Let assume that we have two strings a and b.
(optional) Compare lengths to find longer one.
Iterate over them char by char and compare letters at same index.
If both letters are the same, ignore it. If different, add letter from longer string to result and increment index of the longer string by 1.
What's left in longer string is your result.
Pseudocode:
const a = "aabbccc"
const b = "aabcc"
let res = ""
for (let i = 0, j = 0; i <= a.length; i++, j++) {
if (a[i] !== b[j]) {
res += a[i]
i++
}
}
console.log(res)
More modern and elegant way using high order functions:
const a = "aabbccc"
const b = "aabcc"
const res = [...a].reduce((r, e, i) => e === b[i - r.length] ? r : r + e, "")
console.log(res)
I tried to deal with this problem over month. I need to do many replacements (over 10 millions) in one big string (String ^). Also I need to do it fast. My way was correctly but program was running over 30 minutes.
Problem:
I have a table of changes to do: [strWas1, strWillBe1, strWas2, strWillBe2, ..., strWas10^7, strWillBe10^7]. Also I have one big string which can contain some of strWasN but it also can contain something-elsestrWas1 and I don't want to change it because "something-elsestrWas1" is not "strWas1".
For example String is:
"I have two dogs, three notdogs, also dogsikong, 5dogs, -dogs. DOGS,
Dogs, DoGs, 33DoGs00"
Now I need to change all isolated "dogs" from letters ("dogs" is strWas1) to "cats" ("cats" is strWillBe1). Result should be:
"I have two cats, three notdogs, also dogsikong, 5cats, -cats. cats,
cats, cats, 33cats00"
My last try was:
array<String^>^ strArray = gcnew array<String^>(9999999);
strArray[0] = gcnew String("dogs");
strArray[1] = gcnew String("cats");
//...
strArray[9999998] = gcnew String("whatReplace");
strArray[9999999] = gcnew String("newText");
bool found = false;
int index;
bool doThis = true;
String ^ notAllowed = u8"aąbcćdeęfghijklłmnńoópqrsśtuvwxyzźżAĄBCĆDEĘFGHIJKLŁMNŃOÓPQRSŚTUVWXYZŹŻёйцукенгшщзхъфывапролджэячсмитьбюЁЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ";
String ^ text = u8"I have two dogs, three notdogs, also dogsikong, 5dogs, -dogs. DOGS, Dogs, DoGs, 33DoGs00";
for (int i = 0; i < 9999999; i+=2) {
while (found = text->Contains(strArray[i])) {
index = text->IndexOf(strArray[i]);
MessageBox::Show(index.ToString());
doThis = true;
if (index == 0) {
for (int j = 0; j < notAllowed->Length; j++) {
if (text->Substring(strArray[i]->Length, 1) == notAllowed->Substring(j, 1)) doThis = false;
}
}
else if (text->Length - index - strArray[i]->Length) {
for (int j = 0; j < notAllowed->Length; j++) {
if (text->Substring(index-1, 1) == notAllowed->Substring(j, 1)) doThis = false;
}
}
else {
for (int j = 0; j < notAllowed->Length; j++) {
if ((text->Substring(index - 1, 1) == notAllowed->Substring(j, 1)) || (text->Substring(index+strArray[i]->Length,1)== notAllowed->Substring(j, 1))) doThis = false;
}
}
if (doThis) {
text = text->Substring(0, index) + strArray[i + 1] + text->Substring(index + strArray[i]->Length, text->Length - index - strArray[i]->Length);
}
}
}
But this is working for endlessly
New version (thanks to Vlad Feinstein):
array<String^>^ strArray = gcnew array<String^>(10);
strArray[0] = gcnew String("dogs");
strArray[1] = gcnew String("cats");
strArray[2] = gcnew String("dogs");
strArray[3] = gcnew String("cats");
strArray[4] = gcnew String("dogs");
strArray[5] = gcnew String("cats");
strArray[6] = gcnew String("dogs");
strArray[7] = gcnew String("cats");
strArray[8] = gcnew String("dogs");
strArray[9] = gcnew String("cats");
bool found = false;
int index;
bool doThis = true;
String ^ text = u8"I have two dogs, three notdogs, also dogsikong, 5dogs, -dogs. DOGS, Dogs, DoGs, 33DoGs00";
for (int i = 0; i < 10; i += 2)
{
int index = 0;
while ((index = text->ToLower()->IndexOf(strArray[i]->ToLower(), index)) != -1)
{
doThis = true;
// is there one more char?
if (index + strArray[i]->Length < text->Length)
{
if (Char::IsLetter(text[index+strArray[i]->Length]))
doThis = false;
}
// is there previous char?
if (index > 0)
{
if (Char::IsLetter(text[index - 1]))
doThis = false;
}
if (doThis)
text = text->Substring(0, index) + strArray[i + 1] +
text->Substring(index + strArray[i]->Length);
Debug::WriteLine(text);
index++;
}
}
Of course it is still not so quick version. Quick version wrote David Yaw.
There's a much better way to do this, rather than blindly checking each of one million replacement strings. Let .Net hash the strings, and have it do the checking that way.
If we receive the find & replace strings as a Dictionary, we can use .Net's hash lookups to find the strings that we need to replace.
If we step through each character in the string, it might be the beginning of a 5-character 'search for' string, or the beginning of a 4-character 'search for' string, etc, or it might not be part of a 'search for' string at all, in which case it'll get copied to the output directly. If we do find a 'search for' string, we'll write the replacement to the output, and mark the appropriate number of input characters as consumed.
Based on your description, it appears you want a case-insensitive comparison when searching for strings. You can use case-sensitive or -insensitive, just specify whatever you like when you construct the Dictionary.
String^ BigFindReplace(
String^ originalString,
Dictionary<String^, String^>^ replacementPairs)
{
// First, get the lengths of all the 'search for' strings in the replacement pairs.
SortedSet<int> searchForLengths;
for each (String^ searchFor in replacementPairs->Keys)
{
searchForLengths.Add(searchFor->Length);
}
// Searching for an empty string isn't valid: remove length zero, if it's there.
searchForLengths.Remove(0);
StringBuilder result;
// Step through the input string. For each character:
// A) See if the character is the beginning of one of the 'search for' strings.
// If so, then insert the 'replace with' string into the output buffer.
// Skip over this character and the rest of the 'search for' string that we found.
// B) If it's not the beginning of a 'search for' string, copy it to the output buffer.
for(int i = 0; i < originalString->Length; i++)
{
bool foundSomething = false;
int foundSomethingLength = 0;
for each (int len in searchForLengths.Reverse())
{
if (i > (originalString->Length - len))
{
// If we're on the last 4 characters of the string, we can ignore
// all the 'search for' strings that are 5 characters or longer.
continue;
}
String^ substr = originalString->Substring(i, len);
String^ replaceWith;
if (replacementPairs->TryGetValue(substr, replaceWith))
{
// We found the section of the input string that we're looking at in our
// 'search for' list! Inser the 'replace with' into the output buffer.
result.Append(replaceWith);
foundSomething = true;
foundSomethingLength = len;
break; // don't try to find more 'search for' strings.
}
}
if(foundSomething)
{
// We found & already inserted the replacement text. Just increment
// the loop counter to skip over the rest of the characters of the
// found 'search for' text.
i += (foundSomethingLength - 1); // "-1" because the for loop has its own "+1".
}
else
{
// We didn't find any of the 'search for' strings,
// so this is a character that just gets copied.
result.Append(originalString[i]);
}
}
return result.ToString();
}
My test app:
int main(array<System::String ^> ^args)
{
String^ text = "I have two dogs, three notdogs, also dogsikong, 5dogs, -dogs. DOGS, Dogs, DoGs, 33DoGs00";
Dictionary<String^, String^>^ replacementPairs =
gcnew Dictionary<String^, String^>(StringComparer::CurrentCultureIgnoreCase);
replacementPairs->Add("dogs", "cats");
replacementPairs->Add("pigs", "cats");
replacementPairs->Add("mice", "cats");
replacementPairs->Add("rats", "cats");
replacementPairs->Add("horses", "cats");
String^ outText = BigFindReplace(text, replacementPairs);
Debug::WriteLine(outText);
String^ text2 = "I have two dogs, three notpigs, also miceikong, 5rats, -dogs. RATS, Horses, DoGs, 33DoGs00";
String^ outText2 = BigFindReplace(text, replacementPairs);
Debug::WriteLine(outText2);
return 0;
}
Output:
I have two cats, three notcats, also catsikong, 5cats, -cats. cats, cats, cats, 33cats00
I have two cats, three notcats, also catsikong, 5cats, -cats. cats, cats, cats, 33cats00
Edit: Whole words only
OK, so we need to substitute whole words only. To do that, I wrote a helper method to split a string into words & nonwords. (This is different from the built-in String::Split method: String::Split doesn't return the delimiters, and we need them here.)
Once we have an array of strings, where every string is either a word or a bunch of non-word characters (e.g., separators, whitespace, etc.), then we can run each of those through the Dictionary. Because we're doing a whole word at a time, not just a single letter at a time, this is more efficient.
array<String^>^ SplitIntoWords(String^ input)
{
List<String^> result;
StringBuilder currentWord;
bool currentIsWord = false;
for each (System::Char c in input)
{
// Words are made up of letters. Word separators are made up of
// everything else (numbers, whitespace, punctuation, etc.)
bool nextCharIsWord = Char::IsLetter(c);
if(nextCharIsWord != currentIsWord)
{
if(currentWord.Length > 0)
{
result.Add(currentWord.ToString());
currentWord.Clear();
}
currentIsWord = nextCharIsWord;
}
currentWord.Append(c);
}
if(currentWord.Length > 0)
{
result.Add(currentWord.ToString());
currentWord.Clear();
}
return result.ToArray();
}
String^ BigFindReplaceWords(
String^ originalString,
Dictionary<String^, String^>^ replacementPairs)
{
StringBuilder result;
// First, separate the input string into an array of words & non-words.
array<String^>^ asWords = SplitIntoWords(originalString);
// Go through each word & non-word that came out of the split. If a word or
// non-word is in the replacement list, add the replacement to the output.
// Otherwise, add the word/nonword to the output.
for each (String^ word in asWords)
{
String^ replaceWith;
if (replacementPairs->TryGetValue(word, replaceWith))
{
result.Append(replaceWith);
}
else
{
result.Append(word);
}
}
return result.ToString();
}
My test app:
int main(array<System::String ^> ^args)
{
String^ text = "I have two dogs, three notdogs, also dogsikong, 5dogs, -dogs. DOGS, Dogs, DoGs, 33DoGs00";
array<String^>^ words = SplitIntoWords(text);
for (int i = 0; i < words->Length; i++)
{
Debug::WriteLine("words[{0}] = '{1}'", i, words[i]);
}
Dictionary<String^, String^>^ replacementPairs =
gcnew Dictionary<String^, String^>(StringComparer::CurrentCultureIgnoreCase);
replacementPairs->Add("dogs", "cats");
replacementPairs->Add("pigs", "cats");
replacementPairs->Add("mice", "cats");
replacementPairs->Add("rats", "cats");
replacementPairs->Add("horses", "cats");
String^ outText = BigFindReplaceWords(text, replacementPairs);
Debug::WriteLine(outText);
String^ text2 = "I have two dogs, three notpigs, also miceikong, 5rats, -dogs. RATS, Horses, DoGs, 33DoGs00";
String^ outText2 = BigFindReplaceWords(text2, replacementPairs);
Debug::WriteLine(outText2);
return 0;
}
Results:
words[0] = 'I'
words[1] = ' '
words[2] = 'have'
words[3] = ' '
words[4] = 'two'
words[5] = ' '
words[6] = 'dogs'
words[7] = ', '
words[8] = 'three'
words[9] = ' '
words[10] = 'notdogs'
words[11] = ', '
words[12] = 'also'
words[13] = ' '
words[14] = 'dogsikong'
words[15] = ', 5'
words[16] = 'dogs'
words[17] = ', -'
words[18] = 'dogs'
words[19] = '. '
words[20] = 'DOGS'
words[21] = ', '
words[22] = 'Dogs'
words[23] = ', '
words[24] = 'DoGs'
words[25] = ', 33'
words[26] = 'DoGs'
words[27] = '00'
I have two cats, three notdogs, also dogsikong, 5cats, -cats. cats, cats, cats, 33cats00
I have two cats, three notpigs, also miceikong, 5cats, -cats. cats, cats, cats, 33cats00
There are a lot of issues in your code the may cause problems but main logical error is:
while (found = text->Contains(strArray[i]))
should be
while (found == text->Contains(strArray[i]))
Since == is the comparison operator while = is an assignment operator. So you are always assigning, therefore your while loop in an infinite loop.
Hm... No?
while (found == text->Contains(strArray[i]))
is for comparison. But I didn't compute found before. So I calculate found in while and checking if it is true. It is allowed.
while (found = text->Contains(strArray[i]))
is exactly what:
found = text->Contains(strArray[i])
while (found==true)
At least in normal C++ it is working. Here I don't have problem with this also.
Пётр Васильевич, a few suggestions:
Replace Substring(x, 1) with Char[x].
Throw away your notAllowed string and use .NET's Char.IsLetter Method, or at least break out of your for() loops when you set doThis = false;
If you need a substring from index to the end of string, you don't need to calculate the length; just use a form with one parameter: public string Substring(int startIndex)
Don't use text->Contains(); you need to call text->IndexOf() anyway, just compare that index to -1.
10 million words??? There aren't that many in English and Russian combined!
Use two-parameters form of String.IndexOf Method (Char, Int32), to specify where to start the search (from the position of the previously found word), to avoid searching the beginning of the string over and over. Something like that:
for (int i = 0; i < 9999999; i += 2)
{
int index = 0;
while ((index = text->IndexOf(strArray[i], index)) != -1)
{
doThis = true;
// is there one more char?
if (index + strArray[i]->Length < text->Length)
{
if(Char.IsLetter(text->Char[strArray[i]->Length]))
doThis = false;
}
// is there previous char?
if (index > 0)
{
if (Char.IsLetter(text->Char[index - 1]))
doThis = false;
}
if (doThis)
text = text->Substring(0, index) + strArray[i + 1] +
text->Substring(index + strArray[i]->Length);
}
}
In your while() loop, collect the indexes of the found strings into an array, then do all replacement of the same word in one pass. That is particularly useful if there are multiple occurances of the same word in text.
I am Persian and j2me do not have good support for persian font.
I will create a native font library that get bitmap font and paint my persian text in desplay. But I have a problem.
In english each letter is a set consist shap and uncode. Like (a , U+0061)
But in persian a char may have several shape. for example letter 'ب' in persian alphabet can be:
آب --when it is separate letter in a word
به --when it is start letter in a word
...
How can I get other form of a letter from font file?
I am a persian developer and I had the same problem in about 4 years ago.You have some way to solve this problem:
1-using custom fonts.
2-reshape your text before display it.
A good article in about first,is "MIDP Terminal Emulation, Part 3: Custom Fonts for MIDP ".But for arabic letters I think that is not simple.
In about second way,say you would to replace any character in your text with correct character.This means when you have:
String str = "به";
If get str characters they will be look like:
{1576,1607} that is like "ب ه" instead of "به".So you would to replace incorrect Unicode with correct Unicode codes(in this case correct characters are: {65169, 65258}).You can use "Arabic Reshapers" even reshapers that designed for android!I saw 2 link for this reshapers:1-github 2-Arabic Android(I'm persian developer and so I do not try them,instead I create classes with the same idea as they have).
With using a good reshaper also you may have problem with character arranging from left to right instead of right to left.(some phones draw characters from left to right and other from right to left).I use below class to detect that ordering is true(from right to left) or not:
public class DetectOrdering{
public static boolean hasTrueOrdering()
{
boolean b = false;
try {
char[] chArr = {65169, 65258};
String str = new String(chArr);
System.out.println(str);
int width = f1.charWidth(chArr[1]) / 2;
int height = f1.getHeight();
image1 = Image.createImage(width, height);
image2 = Image.createImage(width, height);
Graphics g1 = image1.getGraphics();
Graphics g2 = image2.getGraphics();
g1.drawString(str, 0, 0, 0);
g2.drawChar(chArr[1], 0, 0, 0);
int[] im1 = new int[width * height];
int[] im2 = new int[width * height];
image1.getRGB(im1, 0, width, 0, 0, width, height);
image2.getRGB(im2, 0, width, 0, 0, width, height);
if (areEqualIntArrrays(im1, im2)) {
b = true;
} else {
b = false;
}
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
private static boolean areEqualIntArrrays(int[] i1, int[] i2) {
if (i1.length != i2.length) {
return false;
} else {
for (int i = 0; i < i1.length; i++) {
if (i1[i] != i2[i]) {
return false;
}
}
}
return true;
}
}
If DetectOrdering.hasTrueOrdering() returns true,sure that phone draw Arabic characters from right to left and display your String.If returns false it draws from left to right.If phone draws Arabic character from left to right you would to reverse string after reshape it and then you can display it.
You can use one alphabet.png for the direct unicode mappings (those where the persian char does not change because of the neighbor chars). If your characters are monospaced, you may start with below class, as seen at http://smallandadaptive.blogspot.com.br/2008/12/custom-monospaced-font.html:
public class MonospacedFont {
private Image image;
private char firstChar;
private int numChars;
private int charWidth;
public MonospacedFont(Image image, char firstChar, int numChars) {
if (image == null) {
throw new IllegalArgumentException("image == null");
}
// the first visible Unicode character is '!' (value 33)
if (firstChar <= 33) {
throw new IllegalArgumentException("firstChar <= 33");
}
// there must be at lease one character on the image
if (numChars <= 0) {
throw new IllegalArgumentException("numChars <= 0");
}
this.image = image;
this.firstChar = firstChar;
this.numChars = numChars;
this.charWidth = image.getWidth() / this.numChars;
}
public void drawString(Graphics g, String text, int x, int y) {
// store current Graphics clip area to restore later
int clipX = g.getClipX();
int clipY = g.getClipY();
int clipWidth = g.getClipWidth();
int clipHeight = g.getClipHeight();
char[] chars = text.toCharArray();
for (int i = 0; i < chars.length; i++) {
int charIndex = chars[i] - this.firstChar;
// current char exists on the image
if (charIndex >= 0 && charIndex <= this.numChars) {
g.setClip(x, y, this.charWidth, this.image.getHeight());
g.drawImage(image, x - (charIndex * this.charWidth), y,
Graphics.TOP | Graphics.LEFT);
x += this.charWidth;
}
}
// restore initial clip area
g.setClip(clipX, clipY, clipWidth, clipHeight);
}
}
And change it to use a different char_uxxxx.png file for each persian char that changes because of the neighbor chars.
When parsing your string, before painting, you must check which png file is appropriate to use. Hope this is a good place to start.
A string is called a square string if it can be obtained by concatenating two copies of the same string. For example, "abab", "aa" are square strings, while "aaa", "abba" are not. Given a string, how many subsequences of the string are square strings? A subsequence of a string can be obtained by deleting zero or more characters from it, and maintaining the relative order of the remaining characters.The subsequence need not be unique.
eg string 'aaa' will have 3 square subsequences
Observation 1: The length of a square string is always even.
Observation 2: Every square subsequence of length 2n (n>1) is a combination of two shorter subsequences: one of length 2(n-1) and one of length 2.
First, find the subsequences of length two, i.e. the characters that occur twice or more in the string. We'll call these pairs. For each subsequence of length 2 (1 pair), remember the position of the first and last character in the sequence.
Now, suppose we have all subsequences of length 2(n-1), and we know for each where in the string the first and second part begins and ends. We can find sequences of length 2n by using observation 2:
Go through all the subsequences of length 2(n-1), and find all pairs where the first item in the pair lies between the last position of the first part and the first position of the second part, and the second item lies after the last position of the second part. Every time such a pair is found, combine it with the current subsequence of length 2(n-2) into a new subsequence of length 2n.
Repeat the last step until no more new square subsequences are found.
Psuedocode:
total_square_substrings <- 0
# Find every substring
for i in 1:length_of_string {
# Odd strings are not square, continue
if((length_of_string-i) % 2 == 1)
continue;
for j in 1:length_of_string {
# Remove i characters from the string, starting at character j
substring <- substr(string,0,j) + substr(string,j+1,length_of_string);
# Test all ways of splitting the substring into even, whole parts (e.g. if string is of length 15, this splits by 3 and 5)
SubstringTest: for(k in 2:(length_of_substring/2))
{
if(length_of_substring % k > 0)
continue;
first_partition <- substring[1:partition_size];
# Test every partition against the first for equality, if all pass, we have a square substring
for(m in 2:k)
{
if(first_partition != substring[(k-1)*partition_size:k*partition_size])
continue SubstringTest;
}
# We have a square substring, move on to next substring
total_square_substrings++;
break SubstringTest;
}
}
}
Here's a solution using LINQ:
IEnumerable<string> input = new[] {"a","a","a"};
// The next line assumes the existence of a "PowerSet" method for IEnumerable<T>.
// I'll provide my implementation of the method later.
IEnumerable<IEnumerable<string>> powerSet = input.PowerSet();
// Once you have the power set of all subsequences, select only those that are "square".
IEnumerable<IEnumerable<string>> squares = powerSet.Where(x => x.Take(x.Count()/2).SequenceEqual(x.Skip(x.Count()/2)));
Console.WriteLine(squares);
And here is my PowerSet extension method, along with a "Choose" extension method that is required by PowerSet:
public static class CombinatorialExtensionMethods
{
public static IEnumerable<IEnumerable<T>> Choose<T>(this IEnumerable<T> seq, int k)
{
// Use "Select With Index" to create IEnumerable<anonymous type containing sequence values with indexes>
var indexedSeq = seq.Select((Value, Index) => new {Value, Index});
// Create k copies of the sequence to join
var sequences = Enumerable.Repeat(indexedSeq,k);
// Create IEnumerable<TypeOf(indexedSeq)> containing one empty sequence
/// To create an empty sequence of the same anonymous type as indexedSeq, allow the compiler to infer the type from a query expression
var emptySequence =
from item in indexedSeq
where false
select item;
var emptyProduct = Enumerable.Repeat(emptySequence,1);
// Select "Choose" permutations, using Index to order the items
var indexChoose = sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from accseq in accumulator
from item in sequence
where accseq.All(accitem => accitem.Index < item.Index)
select accseq.Concat(new[] { item }));
// Select just the Value from each permutation
IEnumerable<IEnumerable<T>> result =
from item in indexChoose
select item.Select((x) => x.Value);
return result;
}
public static IEnumerable<IEnumerable<T>> PowerSet<T>(this IEnumerable<T> seq)
{
IEnumerable<IEnumerable<T>> result = new[] { Enumerable.Empty<T>() };
for (int i=1; i<=seq.Count(); i++)
{
result = result.Concat(seq.Choose<T>(i));
}
return result;
}
}
I initially derive all possible sub-sequences and then i will check if the derived sub-sequence is a square sub-sequence or not
import java.io.*;
import java.util.*;
public class Subsequence {
static int count;
public static void print(String prefix, String remaining, int k) {
if (k == 0) {
//System.out.println(prefix);
if(prefix.length() %2 == 0 && check(prefix) != 0 && prefix.length() != 0)
{
count++;
//System.out.println(prefix);
}
return;
}
if (remaining.length() == 0)
return;
print(prefix + remaining.charAt(0), remaining.substring(1), k-1);
print(prefix, remaining.substring(1), k);
}
public static void main(String[] args)
{
//String s = "aaa";
Scanner sc = new Scanner(System.in);
int t=Integer.parseInt(sc.nextLine());
while((t--)>0)
{
count = 0;
String s = sc.nextLine();
for(int i=0;i<=s.length();i++)
{
print("",s,i);
}
System.out.println(count);
}
}
public static int check(String s)
{
int i=0,j=(s.length())/2;
for(;i<(s.length())/2 && j < (s.length());i++,j++)
{
if(s.charAt(i)==s.charAt(j))
{
continue;
}
else
return 0;
}
return 1;
}
}
import java.io.*;
import java.util.*;
public class Solution {
/*
Sample Input:
3
aaa
abab
baaba
Sample Output:
3
3
6
*/
public static void main(String[] args) {
//Creating an object of SquareString class
SquareString squareStringObject=new SquareString();
Scanner in = new Scanner(System.in);
//Number of Test Cases
int T = in.nextInt();
in.nextLine();
String[] inputString=new String[T];
for(int i=0;i<T;i++){
// Taking input and storing in String Array
inputString[i]=in.nextLine();
}
for(int i=0;i<T;i++){
//Calculating and printing the number of Square Strings
squareStringObject.numberOfSquareStrings(inputString[i]);
}
}
}
class SquareString{
//The counter maintained for keeping a count of Square Strings
private int squareStringCounter;
//Default Constructor initialising the counter as 0
public SquareString(){
squareStringCounter=0;
}
//Function calculates and prints the number of square strings
public void numberOfSquareStrings(String inputString){
squareStringCounter=0;
//Initialising the string part1 as a single character iterated over the length
for(int iterStr1=0;iterStr1<inputString.length()-1;iterStr1++){
String str1=""+inputString.charAt(iterStr1);
String str2=inputString.substring(iterStr1+1);
//Calling a recursive method to generate substring
generateSubstringAndCountSquareStrings(str1,str2);
}
System.out.println(squareStringCounter);
}
//Recursive method to generate sub strings
private void generateSubstringAndCountSquareStrings(String str1,String str2){
for(int iterStr2=0;iterStr2<str2.length();iterStr2++){
String newStr1=str1+str2.charAt(iterStr2);
if(isSquareString(newStr1)){
squareStringCounter++;
}
String newStr2=str2.substring(iterStr2+1);
generateSubstringAndCountSquareStrings(newStr1,newStr2);
}
}
private boolean isSquareString(String str){
if(str.length()%2!=0)
return false;
String strPart1=str.substring(0,str.length()/2);
String strPart2=str.substring(str.length()/2);
return strPart1.equals(strPart2);
}
}
I've got the following method:
public static string ReturnFormat(string input, int maxLength, int decimalPrecision, char formatChar)
{
string[] format = new string[2];
string[] inputs = new string[2];
inputs = input.Split(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]);
if (input.Length > maxLength)
{
int offset = 0;
int counter = 0;
if (inputs[0].Length > maxLength - (1 + decimalPrecision))
{
offset = maxLength - (1 + decimalPrecision);
}
else
offset = inputs[0].Length;
for (int i = 0; i < offset; i++)
{
format[0] += formatChar;
if (counter < decimalPrecision)
{
format[1] += '0';
counter++;
}
}
System.Windows.Forms.MessageBox.Show("{0:" + format[0] + "." + format[1] + "}");
return String.Format(CultureInfo.CurrentCulture, "{0:" + format[0] + "." + format[1] + "}", input);
}
else
return input;
}
Which say I'm using as:
ReturnFormat("12.3456789011243", 10, 2, '#') // format is {0:##.00} // output 12.3456789011243
ReturnFormat("12345678901.1243", 10, 2, '#') // format is {0:#######.00} // output 12345678901.1243
Now my issue is that the input string is not formatted well, still the format strig appears to be ok.
Any ideas of what I'm doing wrong?
Your input is a String not a Double, so it gets formatted like a string: the formatting does not know about decimal places in that case.
You could use Double.Parse() to transform the string into a Double value, but take care of using the right culture.
Another thing, is there a specific reason for not using the more natural format {0:0.00} in both cases? If you really mean to use a placeholder for digits then # is ok, otherwise 0 is best.
Tested solution (beware it truncates and does not round) I needed some time to understand what was actually wanted:
public static string ReturnFormat(string input, int maxLength, int decimalPrecision)
{
if (input.Length <= maxLength)
return input;
Char separator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0];
string[] inputs = input.Split(separator);
// NB: truncating rather than rounding
if (inputs[1].Length > decimalPrecision)
inputs[1] = inputs[1].Substring(0, decimalPrecision);
int digits = (maxLength - decimalPrecision - 1);
// NB: truncating rather than rounding, adding ~ to signalize the
// presence of missing significant digits
if (inputs[0].Length > digits)
inputs[0] = inputs[0].Substring(0, digits-1) + "~";
return inputs[0] + separator + inputs[1];
}