lundi 20 avril 2015

Question marks in output string

I'm trying to replace some chars in my string but somehow I'm getting questions marks instead of chars.

StreamReader sr = new StreamReader(@"xxx.txt");
            string userInput = sr.ReadToEnd();
            string[] s = userInput.Split(' ', ',', '.', '\r', '\n');
            for (int i = 0; i < s.Length; i++)
            {
                if(s[i].Contains('ä'))
                {
                    s[i] = s[i].Replace('ä', 'a');
                }
                if (s[i].Contains('ü'))
                {
                    s[i] = s[i].Replace('ü', 'u');
                }
                if (s[i].Contains('ö'))
                {
                    s[i] = s[i].Replace('ö', 'o');
                }
            }

            foreach (var item in s)
            {
                Console.Write(item + " ");
            }
            Console.ReadKey();

What I'm expecting as output is something like this :a a a a a. What I'm actually getting: ? ? ? ? ?

reverse c style string [duplicate]

This question already has an answer here:

I know this question has been asked many times but I am completely stuck.

EDIT: This question is different from previous questions because the problem was not with the code for the reverse function, but rather what types of values can be passed to the reverse function (ie. array vs pointer) .. see answers below for more info.

I am simply trying to reverse a c style string. I have taken copied and pasted the code to do so directly from Cracking the Coding Interview. (see below)

void reverse(char *str) {
    char * end = str;
    char tmp;
    if (str) {
        while (*end) {
            ++end;
        }
        --end;
        while (str < end) {
            tmp = *str;
            *str++ = *end;
            *end-- = tmp;
        }
    }
}

This does not work for me. I am very new to C so perhaps I am compiling the code wrong. My main function looks like:

int main(int argc, char *argv[])
{   
    char *string = "foobar";
    reverse(string);
    printf("%s\n", string);

    return 0;
}

I am using Cygwin with Windows 8.1 and on the command line I am running:

gcc ex1.c -Wall -o exe1
./exe1

Everytime I get a pop up from windows saying "exe1.exe has stopped working". I tried putting a print statement in the while loop to try debug and see what is going on. It reaches the while loop once before the windows pop up appears.

What am I doing wrong?

Thanks!

Printing an array in Java with toString() [duplicate]

This question already has an answer here:

Im trying to print out my array without all of the brackets and commas so I'm attempting to override the toString() method; However im getting an output of [I@5c647e05. Sorry if my post has bad form this is my first post here.

Here is my code.

import java.util.Scanner;
import java.util.Arrays;
import java.io.*;
import java.util.*;

public class halfAdder {
    public static int[] binary = new int[2];

    public static void main(String[] args) {
        // Declaring booleans for the adder
        int sum = 0;
        int carry = 0;
        boolean a = false;
        boolean b = false;
        int tempA = 0;
        int tempB = 0;
        int notA = 0;
        int notB = 0;


        // Collecting all the information needed from the user
        Scanner console = new Scanner(System.in);

        System.out.print("Please enter your input for A: ");
        tempA = console.nextInt();
        System.out.print("Please enter an input for B: ");
        tempB = console.nextInt();


        // Deciding if what we collected as an input is either 0 or 1
        if(tempA == 0)
        {
            a = false;
            notA = 1;
            System.out.println("A hit first");
        }
        else
        {
            System.out.println("hit second");
            a = true;
            notA = 0;
        }

        if(tempB == 0)
        {
            System.out.println("B hit first");
            b = false;
            notB = 1;
        }
        else
        {
            System.out.println("B hit second");
            b = true;
            notB = 0;
        }

        sum = (notA*tempB)+(tempA*notB);

         if(tempA == 1 && tempB == 1)
        {
            carry = 1;
            sum = 0;
        } 

        binary[0] = carry;
        binary[1] = sum;


        System.out.println("a = " + tempA);
        System.out.println("b = " + tempB);
        System.out.println("not a = " + notA);
        System.out.println("not b = " + notB);
        System.out.println("Sum = " + sum);
        System.out.println("Carry = " + carry);
        System.out.println(binary.toString());
    }

    public String toString()
    {
        String binaryNumber = "The binary number is: ";

        for(int i = 0; i < binary.length; i++)
        {
            binaryNumber += binary[i];
        }
        return binaryNumber;
    }
}

longest substring, time limit exceeded java

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

public static int lengthOfLongestSubstring(String s) {
    if (s.length()==0)
        return 0;
    int maxlen = 1;

    HashMap<Character, ArrayList<Integer>> check = new HashMap<Character,ArrayList<Integer>>();
    for (int i = 0; i < s.length(); i++) {
        for (int j = i; j < s.length(); j++) {
            if (!check.containsKey(s.charAt(j))) {
                ArrayList<Integer> value= new ArrayList<>();
                value.add(j);
                check.put(s.charAt(j), value);
            }
            else {
                maxlen = Math.max(j - i, maxlen);
                ArrayList<Integer> temp = check.get(s.charAt(j));
                i=temp.get(temp.size()-1);  
              // get the last index(biggest index) of the key value
                check.clear();
                break;
            }
            if(j==s.length()-1) {
                maxlen = Math.max(j - i + 1, maxlen);
            }

        }
    }
    return maxlen;
  }
}

For the last test of long repeatable string, time limit exceeded. Do not know how to optimize. seek for improvement, thanks

Plotting strings vs floats (occurrence of letter codes vs percent composition)

I have a dataset of sequences (long strings of one-letter codes, e.g. "ACDEF ....", for which I have computed the mean occurrence of each letter over a couple thousand sequences. I would like to plot the mean percentage composition of each letter, using the following code:

import numpy as np
import matplotlib.pyplot as plt

res=[] 
freq=[]

for i in codes.values():
    res.append(i)
    freq.append(fraction_composition(i))    
res=np.array(res)
freq=np.array(freq)
freq*=100 

p1=plt.plot(res,freq,'r^--')

The codes.values() refers to the fact that each one letter code is actually part of a key-value pair stored in a dictionary, and I am simply calling a function iteratively so that the mean frequency of each letter is computed. I get the error message:

ValueError: could not convert string to float: C

after calling the plot function. How can this be resolved?

Many thanks

How to split a string on logic operators

I'm needing to parse some user inputs. They're coming to me in the form of clauses ex:

total>=100
name="foo"
bar!="baz"

I have a list of all of the available operators (<, >, <=, !=, = etc) and was using this to build a regex pattern.

My goal is to get each clause split into 3 pieces:

$result=["total", ">=", "100"]
$result=["name", "=", "foo"]
$result=["bar", "!=", "baz"]

My pattern takes all the operators and builds something like this (condensed for length)(this example only matches > and >=:

preg_split("/(?<=>)|(?=>)|(?<=>=)|(?=>=)/", $clause,3)

So a lookbehind and a lookahead for each operator. I had preg_split restrict to 3 groups in case a string contained an operator character (name="<wow>").

My regex works pretty great, however it fails terribly for any operator which includes characters in another operator. For example, >= is never split right because > is matched and split first. The same for != which is matched by =

Here's what I'm getting:

$result=["total", ">", "=100"]
$result=["bar", "!", "=baz"]

Is it possible to use regex to do what I'm attempting? I need to keep track of the operator and can't simply split the string on it (hence the lookahead/behind solution). One possiblity I considered would be to force a space or unusual character around all the operators so that > and >= would become, say, {>} and {>=} if the regex had to match the brackets, then it wouldn't be able to match early like it is now. However, this isn't an elegant solution and it seems like some of the regex masters here might know a better way.

Is regex the best solution or should I use string functions?

This question is somewhat similar, but I don't believe the answer's pseudocode is accurate - I couldn't get it to work well. How to manipulate and validate string containing conditions that will be evaluated by php

C# Reverse a string array without using sort( ) or reverse( )

Hi I am trying to write a method that will reverse a string array onced called. I finished my code , but only get half of the array reversed, leaving the rest unchanged, being stuck on this for hours. so I had to ask on stack as last resort.

    int start;
    string[] sArray = { "Reverse", "this", "string", "type", "array" };
    int end = (sArray.Length-1);
    for (start = 0; start < sArray.Length; start++ )
                {
                    sArray[start] = sArray[end - start];

                    Console.Write(sArray[start]+",");
                }
    //  The output supposed to be : array type string this Reverse
  // However, I keep getting array type string type array.

Any idea can be helpful .

What's the difference between " and '? [duplicate]

This question already has an answer here:

Why does my code work, when I use " in the following code:

for(int i=0;i<7;i++){
        if(grid[row][i]!=0){
            if(player == "yellow"){
                grid[row][i-1] = 'y';
            }
            else if(player == "red"){
                grid[row][i-1] = 'r';
            }
        }
    }

But don't work, when I use ' in the following code:

for(int i=0;i<7;i++){
        if(grid[row][i]!=0){
            if(player == 'yellow'){
                grid[row][i-1] = 'y';
            }
            else if(player == 'red'){
                grid[row][i-1] = 'r';
            }
        }
    }

It is always saying, "Invalid character constant".
- grid is a 2 dimensional char variable
- row is an interger
- player is the super class (window) protected and in the constructor of the super class occupied with the value yellow:

protected String player;

public window() {
    player = "yellow";
}

Split data.frame row into multiple rows based on commas

I am attempting to split a row in a data.frame based on the character sequence ", ". Here's an example:

mydat <- data.frame(v1 = c("name, name2", "name3", "name4, name5"),
                v2 = c("1, 2", "3", "4, 5"), 
                v3 = c(1, 2, 3))

What I would like to end up with is a data.frame like so:

 v1   v2   v3
name  1    1
name2  2   1
name3  3   2
name4  4   2
name5  5   3

Any suggestions?

Scheme: How to convert a charlist to a string

I am stumped. I am trying to convert a charlist back to a string but it keeps failing: Its stupid because when I paste the result from one function into another it works just fine, but if I do it inside the function it fails...

Example: this works

(delete" h ell o ") outputs: '(#\h #\e #\l #\l #\o) (convertToString '(#\h #\e #\l #\l #\o)) outputs: "hello"

but this doesnt work, if the conertToString is called in delete this happens

(delete" hell o") outputs:. . list->string: contract violation expected: (listof char?) given: '(#\l . "o")

    (define deleteCh;driver
 (lambda (s)
(delete(string->list s))))

(define delete
 (lambda (input)
(cond
  [(null? input) input]
  [(equal? (car input) #\space)  (delete(cdr input))]
  [else (convertToString (cons (car input) (delete(cdr input))))];this works without convertToString 
  )
)
)
define convertToString
(lambda (charList)
(list->string charList)))

cout exe file contents from char

I saved all the contents from an exe file to char buffer.

When I tried:

string bufferStr=(string)buffer;
cout<<bufferStr.length();

I got that bufferStr is much smaller than buffer, so I thought since i was reading an exe file that somewhere in there I had read an escape character "\0" or something.

How can I use buffer to cout or even write to a file, without buffer escaping any characters? Thanks

Find string with only partially known value

In an img tag, the src is not a constant value with each page load.

<img src="http:/foo.com/directory/id=(random alphanumeric string ID)">

The quantity of the alphanumeric string generated by the network that created it is generally just over 200 characters.

If this were the only img tag, I would just do getElementsByTagName, but there are plenty of img across the page source. Is there a way to target a tag source by only partial src contents, and then .innerHTML the ID number only? I imagine it would have to be written in such a way that it goes until it encounters the " at the end.

C++ I had input some strings using the getline function, and tried to convert to 'char' using substring to input into a character array. Got this error

Possible incorrect calling of ArrayList index?

So my goal for this program is to create a method that will take a string and an ArrayList as a parameter, it will add the string to the ArrayList and then alphabetize the whole thing and return the alphabetized ArrayList including the string. The line I'm having trouble with is alphabetized.get(x) = arr.get(x); The program won't compile because it doesn't recognize the value x but I state it earlier in the for loop so I'm not really sure why it won't run...

import java.util.Scanner;
import java.util.*  ;

public class TestArrays {

 static Scanner reader = new Scanner(System.in);
  public static void main(String[] args) {

String pat;

ArrayList<String> names = new ArrayList<String>();
names.add("anna");
names.add("bob");
names.add("matthew");
names.add("charles");
names.add("effron");
System.out.print(newArray(names, pat));
  }

public static ArrayList<String> newArray(ArrayList<String> arr, String str){

 List<String> alphabetized = new ArrayList<String>(arr.size());
 arr.add(str);
java.util.Collections.sort(arr);
for (int x=0; x<=arr.size();x++){
alphabetized.get(x) = arr.get(x);
}
return alphabetized;

}
 }

Thanks

JavaFX split string method problems

I'm in the process of creating a GUI for a program I have been working on. I've got most of the main functionality done and I'm now working on a way to load settings from previous runs of the program. To do this I have the GUI create a .txt file when the user submits all their data and settings, and when they run the GUI again they will load their options from this text file (the GUI will find the file on its own as long as the directories they have set up haven't changed). However I'm having some issues splitting the strings in the txt file and I'm not sure where the problem is. Here is the code that's giving me trouble:

        String[] options = fileData[3].split("|");
        String[] basicOptions = options[0].split(":");
        switch (basicOptions[0]) {
            case "yes":
                trimReadsYesBtn.setSelected(true);
                break;
            case "no":
                trimReadsNoBtn.setSelected(true);
                break;
        }

When this part of the code is run, fileData[3] contains the string yes:no:no:human:GRCh38:no:yes:cloud:STAR|Star-settings|(other settings separated by "|")|

The settings to the left of the first | are what I am interested in, but for some reason when I split fileData[3] based on "|", the String[] options becomes an array where each value is an individual letter of fileData[3].

Ex: y,e,s,:,n,o etc.

Is something going wrong when I split the string using | as the regex value? Or is there some other problem that I'm not seeing. Any help is appreciated and obviously if I wasn't clear through any of that explanation just let me know. Thank you!

Files - How to make the computer take into account a sentence instead of words?

I wrote a program in my computer in which i create a file, view records from the file, edit records from the file, delete records, add additional records, and do some minimal processing of data in the records. However, when i type in information for the record. The computer does not take the sentence into account, only a word. How do i change it ? Thank you

Unable to print variable value inside string using Write-Output

This is how my input string ($inputStr) looks like:

{
    "CloudId" : "67f8f457-1c4a-4622-a743-638318af04e3",
    "ComputerName" : "Computer1",
    "DeploymentErrorInfo" : {
        "IsConditionallyTerminating" : null,
        "MomAlertSeverity" : null,
        "DisplayableErrorCode" : null,
        "IsSuccess" : null,
        "DetailedCode" : null,
        "IsMomAlert" : null,
        "DetailedSource" : null,
        "CloudProblem" : null,
        "IsTerminating" : null,
        "DetailedErrorCode" : null,
        "ExceptionDetails" : null,
        "Code" : null,
        "ShowDetailedError" : null,
        "RecommendedActionCLI" : null,
        "ErrorCodeString" : null,
        "IsDeploymentBlocker" : null,
        "ErrorType" : null,
        "RecommendedAction" : null,
        "Problem" : null,
        "MessageParameters" : null
    },
    "GrantedToList" : [],
    "ID" : "00000000-0000-0000-0000-000000000000",
    "LocalAdminUserName" : "administrator",
    "Name" : "Computer1",
    "NewVirtualNetworkAdapterInput" : [],
    "OperatingSystemInstance" : {
        "Architecture" : null,
        "Edition" : null,
        "Description" : null,
        "Version" : null,
        "Name" : null,
        "OSType" : null,
        "ProductType" : null
    },
    "Owner" : {
        "UserName" : null,
        "RoleID" : null,
        "RoleName" : null
    },
    "StampId" : "23e6799c-33d4-45ea-8e4f-49ec7d5f26e0",
    "StartVM" : true,
    "VMNetworkAssignments" : [],
    "VMTemplateId" : "fdc73f71-1c6d-4e8f-9d02-21c7f4756c2d"
}

I am converting this to an object using ConvertFrom-Json command.

$paramObject = ConvertFrom-Json -InputObject $inputStr

I want it to print 'VM Computer1 is ready' but it does not work and it actually prints the whole string:

Write-Host "VM $paramObject.Name is ready" # prints the entire thing
Write-Host 'VM $paramObject.Name is ready' # prints command
Write-Host $paramObject.Name # prints VM Name so I know I am able to get the VM Name.

Java: Why does my String get corrupted over UDP?

I'm sending an UDP-Datagram with only one string as content and I'm creating the packet like this:

String content = ALIVE + "," + clusterName + "," + nodeName + "," + location;
byte[] data = content.getBytes();
packet = new DatagramPacket(data, data.length);

The problem is, when it arrives it has some weird binary data at the end, which can't be displayed as characters (in Sublime Text it just shows several a NUL-symbol).

String data = new String(packet.getData());

I extract the different information parts with a string tokenizer(,) and solved this problem now by just adding another , at the end before sending it. Still I would like to know, where does this data come from?

PHP remove all characters before certain string

I need to grep certain string(with bold) from any string with regular expression.

Sample data:

"drog stabilizatorja Meyle RE 16-16 060 0004/HD"

"koncnik Meyle RE 16-16 020 0013"

"gumica stabilizatorja Meyle RE 16-14 079 9404/S"

I think it would be ok if I cut all characters before first number in string. I am not sure how to do it.

String initialization confusion in java

i was trying to call the main function inside the main function i have tried the following code and got successfully compiled code.

class test
{
  static int i = 0;

  public static void main(String args[])
  {
    String asda[] = {"!2312"};

    if (++i == 1)
      main(asda);
  }
}

But the error occurs in case of the following code:

class test
{
  static int i = 0;

  public static void main(String args[])
  {
    if (++i == 1)
      main({"!2312"});
  }
}

this made me so confused. the confusion is that String array initialization is done like String A[]={"asdf","Asdf"); then why is it giving error in second case. I m using java 8u40. please solve my problem

How to insert and remove strings from tree class and treenode class in C++?

I have a file of strings, each of which is in a separate line. I want to insert these strings to my treenodes. My codes can be compiled fine but when I load my string file, there is a segmentation fault. How do I fix it and are my codes correct to make a tree? If I want to remove each node and print it on screen, what would the remove function be? My header file:

#ifndef TREE_H
#define TREE_H

#include <iostream>
using namespace std;

struct TreeNode
{
    string Key;
    TreeNode *left;
    TreeNode *right;
};

class Tree
{
    private:
        TreeNode *root;

    public:
        Tree();
        ~Tree();
        string Insert(TreeNode *newNode);
        string Delete(string Key);
    private:
        void ClearTree(TreeNode *T);
};

#endif

Here is my cpp file:

#include <iostream>
#include "try1.hxx"
#include<fstream>
#include<string>
#include<sstream>

using namespace std;

Tree::Tree()
{
    root = NULL;
}

Tree::~Tree()
{
    ClearTree(root);
}

void Tree::ClearTree(TreeNode *T)
{
    if(T==NULL) return; 
    if(T->left != NULL) ClearTree(T->left);
    if(T->right != NULL) ClearTree(T->right);
    delete T;
}

string Tree::Insert(TreeNode *newNode)
{
    TreeNode *temp;
    TreeNode *back;

    temp = root;
    back = NULL;

    while(temp != NULL)
    {
        back = temp;
        if(newNode->Key < temp->Key)
            temp = temp->left;
        else
            temp = temp->right;
    }

    if(back == NULL) root = newNode;
    else
    {
        if(newNode->Key < back->Key) back->left = newNode;
        else back->right = newNode;
    }
}

int main(int number_of_arguments, char** arguments)
{
    Tree *theTree;
    TreeNode *newNode;
    theTree = new Tree();

    string line;
    if (number_of_arguments != 2)
    {
        cout << "ERROR: incorrect command line parameters" << endl;
    }

    ifstream myfile;
    myfile.open (arguments[1]);
    if (myfile.is_open())
    {
        while (getline(myfile, line))
        {
            newNode = new TreeNode();
            newNode->Key=line;
            newNode->left = newNode->right = NULL;
            theTree->Insert(newNode);
        }
    }else cout << "The file doesn't exist" << endl;
}

Writing code for Shift Cypher in C# [on hold]

My class lab has us write a Shift Cypher and Sub Cypher methods that are called in a button click event. Below you will find the code for this problem.

Can someone help me out with the two methods in question and also calling those methods in the event handler?

enter code here

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace String_Stuff
{
    public partial class stringForm : Form
    {
      public stringForm()
      {
          InitializeComponent();
        }

        private string SwitchCase(string input)
        {
            string str1 = input;
            string output = str1.ToUpper();

            return output;

        }


       private string Reverse(string input)
        {
            string str1 = input;
            char[] inputArray = input.ToCharArray();
            Array.Reverse(inputArray);
            string output = new string(inputArray);

            return output;
      }

       private string PigLatin(string input)
       {
           // rules: words that begin with a consinant-
           //is moved to the end and "ay" is added.
           // words that begin with a vowel-
           // the sylable "ay" is added to the end of the word.
           // e.g. eagle -> eagleay, apple->appleay.
           string str1 = input;           
           string ay = "ay";
           input = inputTextBox.Text; // already a string, no need to convert
           input = input.Substring(1, input.Length - 1) + input.Substring(0, 1);
           str1 = " the word in Pig Latin is " + input + ay; // need to use Text property to display string
           string output= str1  ;
           return output;
       }                    



        private string ShiftCypher(string input, int shift)
        {
            //Each letter in the word is replaced by a letter some fixed number of positions down the alphabet.
            //For this lab, shift by 3. Example: program, shifted by 3 will become surjudp

            string output = null;
            char[] A = null;
            A = input.ToCharArray();
            int temp;
            for (int i = 0; i < input.Length; i++)
            {
                temp = (int) (A[i] + shift);
                output += (char)temp;
            }


            return output;
        }

        private string SubCypher(string input, string charsToSub)

        {
            //Each letter in the word will be replaced by a letter from the corresponding position 
            //in a substitution alphabet. For this lab use this substitution alphabet: zeroabcdfghijklmnpqstuvwxy. 
            //Example: disk would become ofqh.
            string subAlpha = "zeroabcdfghijklmnpqstuvwxy";
            string str1 = input;
            string subCypher = subAlpha;



            string output = "";
            return output;
        }



        private void transformButton_Click_1(object sender, EventArgs e)
        {
            string input = inputTextBox.Text;

            switchCaseTextBox.Text = SwitchCase(input);
            reverseTextBox.Text = Reverse(input);
            pigLatinTextBox.Text = PigLatin(input);
            shiftTextBox.Text = ShiftCypher(input,shift);
            subTextBox.Text = SubCypher(input, charsToSub);
        }
    }
}

crystal reports 2008 convert string to date time (SQL)

Good day; Recently our software developer made a change to the time and date tables, which resulted in these fields being separated and changed to a "string" format. Now none of my time formulas will display. I emailed them for help and they sent me a SQL expression that looks like this:

CAST   (
    CONVERT(Varchar(10), ATCC_Contacted, 112) + ' ' +   
    CONVERT(Varchar(8), ATCC_Contacted_Time) AS DateTime)

I have attempted to insert this into the report, but it returns a warning; "Failed to retrieve data from the database." and "Failed to retrieve data from the database. Details: ADO Error Code: 0x Source: Microsoft OLE DB Provider for SQL Server Description: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. SQL State: 22007 Native Error: [Database Vendor Code: 242] I am way out of my depth on this one, and would appreciate any advice given. Thank you in advance.

Comma separated string split by length but keeping the comma separation?

I have a string like this "105321,102305,321506,0321561,3215658" and i need to split this string by the comma (,) and with a specific length, so if the length of each string part is 15, the splited array must be like:

105321,102305
321506,0321561
3215658 

I try several ways but i can't find the right approach to do this

Haskell Replace characters in string with string

This is an extension of this question: Haskell replace characters in string

I would like to tweak the following expression to replace a char with a string

let replaceO = map (\c -> if c=='O' then 'X'; else c)

In the end, I would the following results (XX can be a string of any length):

replaceO "HELLO WORLD"
"HELLXX WXXRLD"

How do you check if a string is a palindrome in java?

I am trying to write a program that checks if a string is a palindrome and so far I know I am on the right path but when I enter my code it keeps on running for ever. I don't know what the problem is and would like help finding out the solution. In my program I want the user to enter word or words in the method Printpalindrome and then the program should know if the string is a palindrome or not.

Here is my code:

    Scanner console = new Scanner (System.in);
    String n = console.next(); 
    Printpalindrome(console,n );
     }
    public static void Printpalindrome(Scanner console, String n){
      Scanner in = new Scanner(System.in);       
    String orginal, reverse = "";



   n = in.nextLine();

  int length = n.length();

  for ( int i = length - 1; i >= 0; i-- )
     reverse = reverse + n.charAt(i);

  if (n.equals(reverse))
     System.out.println("Entered string is a palindrome.");  

}}

Extract part of string (till the first semicolon) in R

I have a column containing values of 3 strings separated by semicolons. I need to just extract the first part of the string.

Type <- c("SNSR_RMIN_PSX150Y_CSH;SP_12;I0.00V50HX0HY3000")

What I want is: Get the first part of the string (till the first semicolon).

Output : SNSR_RMIN_PSX150Y_CSH

I tried gsub but not able to understand. Kindly let me know how we can do this efficiently in R.

Repeatedly removing and replacing the occurence of a substring from the input string

I have this homework question : Write a C program to find the new string after repeatedly removing the occurence of the substring foo from the input string using functions by repeatedly replacing each occurence of 'foo' by 'oof'.

This is my code:

#include <stdio.h>
#include <string.h>

void manipulate(char * a)
{
    int i, flag = 0;
    char newstr[100];

    for (i = 0; a[i] != '\0'; i++) {
        if (a[i] == 'f') {
            if ((a[i + 1] != '\0') && (a[i + 1] == 'o')) {
                if ((a[i + 2] != '\0') && (a[i + 2] == 'o')) {
                    i += 3;
                    flag++;
                }
            }
        }
        newstr[i] = a[i];
    }

    for (i = 0; i < flag; i++) {
        strcat(newstr, "oof");
    }

    printf("\nThe output string is %s", newstr);
}

int main()
{
    char a[100];

    printf("Enter the input string");
    scanf("%s",a);
    manipulate(a);

    return 0;
}

I think something is wrong with my code because the expected output is :

Enter the input string
akhfoooo
The output string is akhoooof

But my Actual output is :

Enter the input string
akhfoooo
The output string is akhoof

Could you please rectify the errors in my code?

How to extract a string array from a multidimensional string array and return it within a method - java?

In Java, I have String[][] and I need to return a single row (ie. String array) of this multidimensional data structure. Here is the code I am using:

private static String[] getData(String routeInfo) {
    int i = 0;
    int j = 0;
    for (j=0;j < 3; j++) {
        if (stopsByRoute[j][i].equals(routeInfo)) {
            return stopsByRoute[j][i];
        }
    }
    return null;
}

Here's the String[][] I am working with which is called stopsByRoute (Note: the array isn't complete. It's for testing):

static String[][] stopsByRoute = {
        {"1 Timberlea Express","Main St. and Franklin Ave. Transfer Stn","Eagle Ridge Gate @ Louitit Road","Powder Station"}, 
    {"2 Thickwood Express","Main St. and Franklin Ave. Transfer Stn","Signal Rd. @ Thickwood Shopping Plaza","Westwood School" }, {"3 Morgan Heights"}};

The problem is instead of returning the String[] the method returns a reference.

extract fraction and 2 or 4 digit year from mulitple formated strings

I have 130,000+ plus strings which contain measurements such as 3/4", 1", etc and house number such as 5648 or 222 and then years formatted ilk 02, 92 or 2004 depending upon what the user felt like typing in that day. I also have \ and - in there randomly just to make it more fun.

What I need is: the first measurement value ie 3/4" or 2" and the year 02 or 1997. I have tried multiple splits and replaces but I don't seem to be getting very far. I have most of the measurements pulled out using a split at ". Any help would be nice. Someone suggested regular expressions but I have never used these.

Here are some examples:

3/4"-6235\PE-03, 
1"-8018\ \PE-00, 
3/4"-    \ \PE-2004, 
1"-11769\ \74\COPSET, 
PE-85, 
1"-BLDG 1, 
COMM CABLE

Here is what I have currently.

for featureToTotal in featuresToTotal:
                    id = id + 1
                    # Get each Water Type Time Total 
                    try:                          
                        ValueOne = featureToTotal[1]
                        tmpvalue = ValueOne.replace("\\", "")
                        tmpvalue = tmpvalue.replace("-", " ")
                        tmpvalue = tmpvalue.replace("'", " ")
                        newValue = tmpvalue.decode('string_escape')

                        splitOne = newValue.split('\\')[0]
                        Split2 = splitOne.split('-')[0]                            
                        trysplit = Split2.split('"')[0]
                        #Test for Number                             
                        try:
                            num = trysplit[:1]
                            float(num)
                            strval = str(trysplit)
                            trysplit = strval
                            #featureToTotal[4] = strval
                            #arcpy.AddMessage(str(trysplit)) 
                            #featuresToTotal.updateRow(featureToTotal)
                        except:
                            errstrr = "yep"
                            #print "Nope" + ValueOne +  " " + trysplit

                        buildqury = "INSERT INTO Annos VALUES(" + str(id) + ", ''" + newValue + "'', ''" + trysplit+ "'', ''" + YearTest +  "'')"
                        cur.execute(buildqury)
                    except:
                        strerr = sys.exc_value.message
                        print "Error Splitting  " 

String to bytes in both Python 2 and 3

My function needs to take input as either a string or binary data (e.g., read from a file). If it's a string, I want to convert this to raw data (bytes or bytearray).

In Python 3, I can do data = bytes(data, 'utf8'). However, this fails in Python 2 as it only takes one argument. Vice versa, data = bytes(data) works in Python 2, but not in Python 3 as it complains about needing an encoding to work to.

For the sake of argument, let's say that all input, if it comes as a string, is UTF-8 encoded. Is there then a better way to achieve what I'm looking for than the following monstrosity:

try:
  data = bytes(data, 'utf8')
except:
  data = bytes(data)

n.b., data.encode() works in Py3, but fails in Py2 in the case that the string contains non-ASCII bytes.

comparison of strings and writing back in java

If two strings are same then the string should be written back into another string how can I do it in java?? Like,

if(s1.equals(s2)==0)
{
    s1;
}

Manipulating a user input string in MapReduce

I am beginning to use the Hadoop variant of MapReduce and therefore have zero clue about the ins and outs. I understand how conceptually it's supposed to work.

My problem is to find a specific search string within a bunch of files I have been provided. I am not interested about the files - that's sorted. But how would you go about asking for input? Would you ask within the JobConf section of the program? If so, how would I pass the string into the job?

If it's within the map() function, how would you go about implementing it? Wouldn't it just ask for a search string every time the map() function is called?

Here's the main method and JobConf() section that should give you an idea:

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

    // This produces an output file in which each line contains a separate word followed by
    // the total number of occurrences of that word in all the input files.

    JobConf job = new JobConf();

    FileInputFormat.setInputPaths(job, new Path("input"));
    FileOutputFormat.setOutputPath(job, new Path("output"));

    // Output from reducer maps words to counts.
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(LongWritable.class);

    // The output of the mapper is a map from words (including duplicates) to the value 1.
    job.setMapperClass(InputMapper.class);

    // The output of the reducer is a map from unique words to their total counts.
    job.setReducerClass(CountWordsReducer.class);

    JobClient.runJob(job);
}

And the map() function:

public void map(LongWritable key, Text value, OutputCollector output, Reporter reporter) throws IOException {

    // The key is the character offset within the file of the start of the line, ignored.
    // The value is a line from the file.

    //This is me trying to hard-code it. I would prefer an explanation on how to get interactive input!
    String inputString = "data"; 
    String line = value.toString();
    Scanner scanner = new Scanner(line);

    while (scanner.hasNext()) {
        if (line.contains(inputString)) {
            String line1 = scanner.next();
            output.collect(new Text(line1), new LongWritable(1));
        }
    }
    scanner.close();
}

I am led to believe that I don't need a reducer stage for this problem. Any advice/explanations much appreciated!

How do I write String arrays to a text file in java using Printwriter?

I need help writing some contents of array objects (following are two example of arrays I'm using) to a text file using Printwriter. Any ideas? I'm a beginner, so the simpler the better, thanks!

Astronauts[0][0] = new Passengers(-1, "", 1, 0, 0, "", "", 0, "", "", "", "", "");

Astronauts[0][1] = new Passengers(0, "Pilot", 2424, 14, 0, "Bruce", "Banner", 0, "678-884-6325", "Mom", "678-884-6323","","");

Astronauts[0][2] = new Passengers(0, "Pilot", 1248, 3, 0, "Sally", "Forth", 0, "678-921-1135", "Hannah", "678-921-1130","","");

Astronauts[1][0] = new Passengers(-1, "", 2, 0, 0, "", "", 0, "", "", "", "", "");

Astronauts[1][1] = new Passengers(0, "Pilot", 1022, 55, 0, "Buz", "Aldrin", 0, "404-014-4553", "June", "404-014-4555","","");

Astronauts[1][2] = new Passengers(0, "Pilot", 2813, 8, 0, "Alice", "Dyer", 0, "678-884-6325", "Mom", "678-884-6323","","");

Why new String with UTF-8 contains more bytes

byte bytes[] = new byte[16];
random.nextBytes(bytes);
try {
   return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
   log.warn("Hash generation failed", e);
}

When I generate a String with given method, and when i apply string.getBytes().length it returns some other value. Max was 32. Why a 16 byte array ends up generating a another size byte string ?

But if i do string.length() it returns 16.

Error "Disallowed system call: SYS_kill" as I try to remove all consecutive duplicate elements from a string

The following

#include <iostream>
#include <string>

void remove_duplicates ( std::string & s )
{

   for (std::string::iterator it(s.begin()), offend(s.end()); it != offend; ++it)
   {
      std::string::iterator temp = it;
      while (++it != offend && *it == *temp);
      if ((it-temp)>1) s.erase(temp, it);
   }
}


int main()
{
   std::string str = "aaabbcaaaaa";
   remove_duplicates(str);
   std::cout << str; /* Expected output: "abca" */
   return 0;
}

is producing the error

/usr/local/lib/gcc/i686-pc-linux-gnu/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h:1154: __gnu_cxx::__normal_iterator::other::pointer, std::basic_string<_CharT, _Traits, _Alloc> > std::basic_string<_CharT, _Traits, _Alloc>::erase(__gnu_cxx::__normal_iterator::other::pointer, std::basic_string<_CharT, _Traits, _Alloc> >, __gnu_cxx::__normal_iterator::other::pointer, std::basic_string<_CharT, _Traits, _Alloc> >) [with _CharT = char, _Traits = std::char_traits, _Alloc = std::allocator]: Assertion '__first >= _M_ibegin() && __first <= __last && __last <= _M_iend()' failed.

Disallowed system call: SYS_kill

when I run it on http://ift.tt/1DtkBwR.

Is there a problem with the logic of my function? If so, what is it, and is there a cleaner way to solve the problem?

NSScanner string always nil (EXC_BAD_INSTRUCTION(code=EXC_i386_INVOP,subcode=0x0))

When using NSScanner, the following code:

var s: String?
var b: NSString?
let scn = NSScanner(string: "andgostring")
scn.scanUpToString("go", intoString: &b)
b = NSString(string:"http")
s = b // <--- Crashes here 

...crashes with

EXC_BAD_INSTRUCTION(code=EXC_i386_INVOP,subcode=0x0

How to release std string from memory management duties?

I have a string by value and a function that takes in a char pointer and length and when finished calls a callback which is a lambda expression provided on that function call. I want my string data to be deallocated on that callback -not when scope exits. There is no move into lambda in c++11 and current wrapper implementations I found can not be passed as void(*fun)() function arguments. Are there ways to move string or release it from its memory duties in c++11?

Is there an equivalent to the string function String(format: ...) using Swift formatting

I'm starting to like the Swift string formatting since it uses variable names in the string rather than ambiguous formatting tags like "%@"

I want to load a large string from a file that has Swift-style formatting in it (like this)

Now is the time for all good (who) to come to babble incoherently.

Then I want to feed the contents of that String variable into a statement that lest me replace "(who)" with the contents of the constant/variable who at runtime.

The code below works with a string constant as the formatting string.

let who = "programmers"
let aString = "Now is the time for all good \(who) to come to babble incoherently."

That code does formatting of a quoted string that appears in-line in my code.

Instead I want something like the code

let formatString = "Now is the time for all good %@ to come to babble incoherently."
aString = String(format: formatString, who)

But where I can pass in a Swift-style format string in a constant/variable I read from a file.

Is that possible. I didn't have any luck searching for it since I wasn't exactly sure what search terms to use.

I can always use C-style string formatting and the String class' initWithFormat method if I have to...

How to check if a string consists of 2 integers with a blank space in-between

As the title states, i want to know how i can check if a string consists of 2 integers with a blank space in between them in Java.
As an example:
0 2, should return true.
0 abc, should return false.
abcsd, should return false.
And so on...

If it is to any help, I am getting my string from a text file with a buffered reader. Maybe there is a more direct and easier way?

Thank you in advance

Can I precompile the format string in String.format?

It is well known that String.format() performance is terrible. I see big possible improvements in my (and probably very common) typical case. I print same structure of data many times. Let imagine the structure like "x:%d y:%d z:%d". I expect that the main trouble with String.format() is that it has to always parse formatting string. My question is: Is there some ready made class which would allow to read formatting string only once and then allow to quickly give string when variable parameters filled?? Usage shall look like this:

PreString ps = new PreString("x:%d y:%d z:%d");
String s;
for(int i=0;i<1000;i++){
    s = ps.format(i,i,i); 
}

I know it is possible - following is my quick & dirty example which do what I'm talking about and is about ~10 times faster at my machine:

public interface myPrintable{
    boolean isConst();
    String prn(Object o);
    String prn();
}

public class MyPrnStr implements myPrintable{
    String s;
    public MyPrnStr(String s){this.s =s;}
    @Override public boolean isConst() { return true; }
    @Override public String prn(Object o) { return s; }
    @Override public String prn() { return s; }
}

public class MyPrnInt implements myPrintable{
    public MyPrnInt(){}
    @Override  public boolean isConst() { return false; }
    @Override  public String prn(Object o) { return String.valueOf((Integer)o);  }
    @Override  public String prn() { return "NumMissing";   }
}

public class FastFormat{
    myPrintable[]      obj    = new myPrintable[100];
    int                objIdx = 0;
    StringBuilder      sb     = new StringBuilder();

    public FastFormat() {}

    public void addObject(myPrintable o) {  obj[objIdx++] = o;   }

    public String format(Object... par) {
        sb.setLength(0);
        int parIdx = 0;
        for (int i = 0; i < objIdx; i++) {
            if(obj[i].isConst()) sb.append(obj[i].prn());
            else                 sb.append(obj[i].prn(par[parIdx++]));
        }
        return sb.toString();
    }
}

It is used like this:

FastFormat ff = new FastFormat();
ff.addObject(new MyPrnStr("x:"));
ff.addObject(new MyPrnInt());
ff.addObject(new MyPrnStr(" y:"));
ff.addObject(new MyPrnInt());
ff.addObject(new MyPrnStr(" z:"));
ff.addObject(new MyPrnInt());
for (int i = 0; i < rpt; i++) {
    s = ff.format(i,i,i);
}

when I compare with

long beg = System.nanoTime();
for (int i = 0; i < rpt; i++) {
    s = String.format("x:%d y:%d z:%d", i, i, i);
}
long diff = System.nanoTime() - beg;

I get better times by factor of ~10:

time [ns]: String.format()     (+90,73%)  3 458 270 585 
time [ns]: FastFormat.format() (+09,27%)    353 431 686 

How to test a char array for letters only (including whitespaces)?

I'm making a function for basic information input. This function will be later used to get information and store on disk. I've made two checks. is_alpha and is_digit. The issue with is_alpha is, it return "0" if it detects white space(which is not what i want). I'm taking input for "Name" and obviously it can contain spaces! Can you please tell me how to make a method which checks my char array if it is a name? (Alphabets and white spaces)

class Bankaccount
{
protected:
int id;
char name[50];
char address[100];
char phone_no[50];
static int count;

public:
Bankaccount()
{

    count++;
    id = count;
}



bool is_number(const std::string& s)
{
std::string::const_iterator it = s.begin();
while (it != s.end() && std::isdigit(*it)) ++it;
return !s.empty() && it == s.end();
}
bool is_alpha(const std::string& s)
{
std::string::const_iterator it = s.begin();
while (it != s.end() && std::isdigit(*it)) ++it;
{cin.ignore(); return !s.empty() && it == s.end();}
}

void basics ()
    {system("cls");
    cout << "Enter Name (Letters only): " << endl;
    cin.ignore();
    cin.getline(name,50);


    {cout << "Enter Address: " << endl;
            cin.ignore();
cin.getline(address,100);
    cout << "Enter Phone Number (Digits only): " << endl;
    cin.ignore();
    cin.getline(phone_no,50);
    //CHECK FOR DIGITS ONLY
    bool temp=0;
    temp=is_number(phone_no);
    {while(temp!=1)
        {cout << "ReEnter Phone Number: " << endl;
        cin.ignore();
        cin.getline(phone_no,50);
        temp=is_number(phone_no);
        }
    }//while ends

    }



    {cout << "ReEnter Name: " << endl;
    cin.ignore();
    cin.getline(phone_no,50);

    cout << "Enter Address: " << endl;
            cin.ignore();
cin.getline(address,100);
    cout << "Enter Phone Number (Digits only): " << endl;
    cin.ignore();
    cin.getline(phone_no,50);
    //CHECK FOR DIGITS ONLY
    bool temp;
    temp=is_number(phone_no);
    if (temp==1)
    {}
    else {cout << "ReEnter Phone Number: " << endl;
    cin.ignore();
    cin.getline(phone_no,50);
    }
}

}

String matching using preg_match() in PHP [duplicate]

This question already has an answer here:

I have a string something like this

$str="syx.ypzd [xys.ypd] yup";

I am trying to get the value inside [ ] .

I have a code something like this

preg_match('[xys.ypd]', $str, $Fdesc);
echo $Fdesc[1];

But this is not working

Please let me know where I am going wrong

Thanks & Regards

Count the no. of occurrence of the exact word in a file using java

I have requirement in which I have to find the no. of times a particular word appears in a file. For eg.

String str = "Hi hello how are you. hell and heaven. hell, gjh, hello,sdnc ";

Now in this string I want to count no. of times the word "hell" appeared. The count should include "hell" , "hell," all these words but not "hello". So according to the given string I want the count to be 2.

I used following approaches

1st:

int match = StringUtils.countMatches(str, "hell");

StringUtils is of org.apache.commons.lang3 library

2nd:

int count = 0;
Pattern p = Pattern.compile("hell");
                Matcher m = p.matcher(str);
                while (m.find()) {
                    count++;
                }

3rd

int count =0;
String[] s = str.split(" ");
for(String word: s)
if(word.equals("hell")
count++;

the 1st two approaches gave 4 as answer and the 3rd approach gave 1 as answer.

Please suggest anyway in which I can get 2 as answer and fullfill my requirement.

Adding string variable to xpath c# selenium

I have probably spent a good 8 hours trying to figure this out but am constantly failing. I have searched an age for a solution

I am trying to find an selenium element by partial id match using xpath (c# selenium libraries). The following works perfectly fine. The partial text is sel_1-rowse1

IWebElement elem = wait5.Until(x => x.FindElement(By.XPath("//a[contains(@id,'sel_1-rowsel')]")));   

However when I want to use a variable named partial this does not work

string partial = "sel_1-rowse1";
IWebElement search = wait.Until(x => x.FindElement(By.XPath(String.Format("//a[contains(@id,'{0}')]", partial))));

or

IWebElement search = wait.Until(x => x.FindElement(By.XPath(String.Format("//a[contains(@id,{0})]", partial))));

I have tried single quotes double quotes and escape chars. But cant figure this out. I cant even provide the error as its picking up a valid id. Brain is severely depleted on this one.

Parse Tokens from a String using strtok()

char line[] = "COPY\tSTART\t0\tCOPY";
char *tmp;

tmp = strtok(line, "\t");
printf("%s", tmp);

This code's output is COPY. And when

char line[] = "\tSTART\t0\tCOPY";

Output is START.

But! I want to check there is nothing in front of string START. That is I think \t is first delimiter so output of strtok(line, "\t") is NULL. But real output is START.

Is there any misunderstanding? What can I do?

Java allow Upper and Lower cases

Using java.util.Scanner; I want the console to allow the users to input from upper and lower cases. For example:

if (user.equals("test") {
    System.out.println("hello");
}

But I want the console to accept all type of cases, so the user can input like TEST and maybe TeSt and the console would see that as "test"

Ruby regex method

I need to get the expected output in ruby by using any method like scan or match.

Input string:

  1. "http://ift.tt/1E0RzJL"
  2. "http://ift.tt/1FZLWZf"

Expected:

  1. r12=1,r122=1, r1=1, r124=1
  2. r12=1,r124=1

How can I get the expected output using regex?

Dynamically splitting and joining strings python [duplicate]

This question already has an answer here:

stringlist = somestring.split()
splice = []
for word in stringlist[:-1]:
    splice.append(word + " " + stringlist[stringlist.index(word)+1])

Currently, the above code splits and joins a string into bunches of two. For example, for a string: "this is a string", the splice list will look like: ["this is","is a","a string"].

What I want to do, is to be able to split and join the string dynamically on the basis of a number (for the number of bunches). For 3, the splicelist would be ["this is a","is a string"]

Hex to String in Android(Java)?

Maybe I was sticky in hex to String?I don't know. my code:

final byte[] txValue = intent.getByteArrayExtra(UartService.EXTRA_DATA);

txValue should be byte ?

debug:

Log.d("p1", ""+txValue.toString());

then show me those:

[B@1e631929
[B@9264ae

I don't know how to fix it ? somebody help me ?

dimanche 19 avril 2015

How to split code string properly

I am trying to write a basic lexical analyzer for Java in Python. The problem I am facing right now is splitting a line of string into words/tokens.


Example:



if (x < 3)
{
x = 3;
}
else
{
x = 0;
}


I want this to return a list like this:



["if", "(", "x", "<", "3", ")", ...


But my code is returning



["if", "(x", "<", "3)"]


My Code:



for line in code.readlines():
for word in line.split():
print word


I searched for a solution but only found solutions using regular expressions, is there a way to do this without regular expressions? Because I have no idea how to use them and I do not have enough time right now to learn it...


Any help will be appreciated...


Split string based on a key and delimiter

I have a requirement to split a string based on a key in PL/SQL.


strCode:=empcode:empname:empcontactno;


strval:=101:John:9345723;


I need to write a generic function to split the strval based on the strCode and populate separate variables such var_empcode, var_empname,var_empcontactno for a bunch of records.


Split based on the delimiter is simple enough, but split based on key and populating corresponding variables is tricky, because the strCode is configurable and the function has to be generic to accomodate future changes in the strCode.


Kindly let me know if there is an easy way to work this one out. Thanks.


Launch url from one activity on another activity

I've been trying to make a small WebView app that lets the user search and load websites within it.


Currently my code looks promising in terms of the structure and the reference used, but I have stumbled upon an error which I can't seem to fix. Ive been looking for solutions on how to parse data as a string from my MainActivity class EditText to the WebView on my WebActivity class.


So far I've had no luck, I've tried several websites and have researched more into this but I have no clue what's going on. I even looked up similar answers regarding my situation on StackOverFlow but nothing has worked for me.


This Is the error I'm getting:



04-20 16:56:55.563: D/AndroidRuntime(32040): Shutting down VM
04-20 16:56:55.564: E/AndroidRuntime(32040): FATAL EXCEPTION: main
04-20 16:56:55.564: E/AndroidRuntime(32040): Process: com.thearclabs.carpo, PID: 32040
04-20 16:56:55.564: E/AndroidRuntime(32040): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.thearclabs.carpo/com.thearclabs.carpo.WebActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
04-20 16:56:55.564: E/AndroidRuntime(32040): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
04-20 16:56:55.564: E/AndroidRuntime(32040): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
04-20 16:56:55.564: E/AndroidRuntime(32040): at android.app.ActivityThread.access$800(ActivityThread.java:151)
04-20 16:56:55.564: E/AndroidRuntime(32040): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
04-20 16:56:55.564: E/AndroidRuntime(32040): at android.os.Handler.dispatchMessage(Handler.java:102)
04-20 16:56:55.564: E/AndroidRuntime(32040): at android.os.Looper.loop(Looper.java:135)
04-20 16:56:55.564: E/AndroidRuntime(32040): at android.app.ActivityThread.main(ActivityThread.java:5254)
04-20 16:56:55.564: E/AndroidRuntime(32040): at java.lang.reflect.Method.invoke(Native Method)
04-20 16:56:55.564: E/AndroidRuntime(32040): at java.lang.reflect.Method.invoke(Method.java:372)
04-20 16:56:55.564: E/AndroidRuntime(32040): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
04-20 16:56:55.564: E/AndroidRuntime(32040): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
04-20 16:56:55.564: E/AndroidRuntime(32040): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
04-20 16:56:55.564: E/AndroidRuntime(32040): at com.thearclabs.carpo.WebActivity.<init>(WebActivity.java:9)
04-20 16:56:55.564: E/AndroidRuntime(32040): at java.lang.reflect.Constructor.newInstance(Native Method)
04-20 16:56:55.564: E/AndroidRuntime(32040): at java.lang.Class.newInstance(Class.java:1606)
04-20 16:56:55.564: E/AndroidRuntime(32040): at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
04-20 16:56:55.564: E/AndroidRuntime(32040): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
04-20 16:56:55.564: E/AndroidRuntime(32040): ... 10 more


This is the code in my MainActivity's onCreate method:



super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText searchInput = (EditText) findViewById(R.id.searchInput);
final String webUrl = searchInput.getText().toString();

searchInput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
Intent intent = new Intent(MainActivity.this, WebActivity.class);
intent.putExtra("website", webUrl);
startActivity(intent);
return true;
}
return false;
}
});


And this is my WebActivity code:



public class WebActivity extends Activity {

String webUrl = getIntent().getExtras().getString("webUrl"); // error is coming from here, according the the error log.

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
WebView webView = (WebView) findViewById(R.id.webView);
webView.loadUrl("http://example.com" + webUrl);

// webView.getSettings().setJavaScriptEnabled(true);

}
}

Python Join String to Produce Combinations For All Words in String

If my string is this: 'this is a string', how can I produce all possible combinations by joining each word with its neighboring word?


What this output would look like:



this is a string
thisis a string
thisisa string
thisisastring
this isa string
this isastring
this is astring


What I have tried:



s = 'this is a string'.split()
for i, l in enumerate(s):
''.join(s[0:i])+' '.join(s[i:])


This produces:



'this is a string'
'thisis a string'
'thisisa string'
'thisisastring'


I realize I need to change the s[0:i] part because it's statically anchored at 0 but I don't know how to move to the next word is while still including this in the output.


How can I access only Strings from [0 to 9] outside for loop?

I am trying to write a code that allows me to access String msgbody and place it in an email. However, using the following code only the final String shows up outside the for loop. I searched many times for an answer, and am a bit new to Java.



List<String> urls = new ArrayList<String>();
String msgbody = "";
for (int i = 0; i < urls.size(); i++) {
urls.get(i);
// String msgbody0; - Used to attempt msgbody0 = url.get(i); then msgbody += msgbody0; but only prints first url
int sum = i + 1;
for (j = 1; j < 2 ; j++)
{
msgbody = urls.get(i);

urls.add(msgbody);
System.out.print("("+ sum +")" +"");
System.out.println(msgbody);
}
if(i==9){
break;
}
} // Inside the for loop everything prints properly.

System.out.println(msgbody); // How can i replicate it here?(Outside for loop)

Efficient string building with immutable strings

In C++ there's vector::reserve() to efficiently allocate memory in advance when building a string. Even without it we can build a string in O(n) amortized.


How do we efficiently build strings in languages where strings are immutable, such as python? The naive method of adding an atom at a time, that works fine in C++ in O(n), seems to be O(n^2), generating O(n^2) garbage for the gc.


How can I store the input from a text box in a string?


JTextField player1Text = new JTextField();
player1Text.setSize(400, 400);
inputWindow.add(player1Text);
System.out.println(player1Text.getText().length());


This will print zero, even though I enter some text in the textbox that appears in the window. However,



JTextField player1Text = new JTextField("input");
player1Text.setSize(400, 400);
inputWindow.add(player1Text);
System.out.println(player1Text.getText().length());


This will print 5 because thats the length of "input". What can I do to get the actual input text?


EDIT: This is my whole code right now. I get a nullpointer exception whenever I run it.



public class NamesInterface extends JFrame implements ActionListener {

Player player1;
Player player2;
JTextField player1Text;
JTextField player2Text;
JButton startButton = new JButton("Start");

public NamesInterface() throws UnexpectedFormatException, IOException {

super();
setSize(500, 1000);
setLayout(new BorderLayout());
setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);

JPanel inputWindow = new JPanel();

inputWindow.setSize(500, 200);
inputWindow.setLayout(new GridLayout(3, 1));

inputWindow.add(new JLabel("Enter Player 1 name:"));
JTextField player1Text = new JTextField();
player1Text.setSize(400, 400);
inputWindow.add(player1Text);

inputWindow.add(new JLabel("Enter Player 2 name:"));
JTextField player2Text = new JTextField();
player2Text.setSize(400, 400);
inputWindow.add(player2Text);

startButton.setSize(500, 500);
startButton.addActionListener(this);
inputWindow.add(startButton);

this.add(inputWindow, BorderLayout.CENTER);



this.validate();

}

@Override
public void actionPerformed(ActionEvent e){

if (e.getSource() == startButton) {

System.out.println(player1Text.getText());
System.out.println(player2Text.getText());

System.exit(0);
}
}


Exceptions thrown:



Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at eg.edu.guc.yugioh.gui.NamesInterface.actionPerformed(NamesInterface.java:64)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6525)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3322)
at java.awt.Component.processEvent(Component.java:6290)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4881)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2739)
at java.awt.Component.dispatchEvent(Component.java:4703)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:751)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:702)
at java.awt.EventQueue$3.run(EventQueue.java:696)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:724)
at java.awt.EventQueue$4.run(EventQueue.java:722)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:721)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

How to bind label to first letter of StringProperty?

I have StringProperty that consists of two letters (example: 06) that are constantly changing. I have two labels, which I want to bind to each letter of StringProperty, like label1="0" and label2="6". Is there a way to bind label to specific letter of StringProperty?


Currently my code is:



@FXML
private Label hoursLabel1;

@FXML
private Label hoursLabel2;

private StringProperty hours;

@FXML
private void initialize() {
hoursLabel1.textProperty().bind(hours);
}

Convert string representation of list of objects back to list in python

I have a list of objects, that has been stringified:



u'[<object: objstuff1, objstuff2>, <object: objstuff1, objstuff2>]'


I want to convert this back into a list:



[<object: objstuff1, objstuff2>, <object: objstuff1, objstuff2>]


I've tried using ast.literal_eval(), but unfortunately, it doesn't seem to work if the elements are objects, and I get a syntax error.


Is there any way I can reconvert my string representation of the list of objects back into a list?


Extracting a substring of a string in Python based on presence of another string

common is always present regardless of string. Using that information, I'd like to grab the substring that comes just before it, in this case, "banana":



string = "apple_orange_banana_common_fruit"


In this case, fruit:



string = "fruit_common_apple_banana_orange"


How would I go about doing this in Python?


Scheme: How to find a position of a char in a string

I am trying to find the index of a string where it is equal to a certain character, but I can seem to figure it out. This is what I got so far, but its not working...



`(define getPos


(lambda () (define s (apply string-append myList)) (getPosition pos (string->list s))))



(define getPosition
(lambda (position s)
(if (and (< position (length s)) (equal? (car s) #\space))
((set! pos (+ pos 1)) (getPosition (cdr s) pos));increment the positon and continue the loop
pos;else
)


) )


(define length (lambda (s);the value s must be coverted to a string->list when passed in (cond ((null? s) 0) (else (+ 1 (length (cdr s)))) ) ) )


Take file contents and put it into a string in C++

I'm using OpenGL and I need the contents of VertexShader.glsl to be put into a std::string


I've looked at the related StackOverflow posts about this but I don't really know how to match together data types and stuff to make it work.


Take for example this from Read file-contents into a string in C++



#include <fstream>
#include <string>

int main(int argc, char** argv)
{

std::ifstream ifs("myfile.txt");
std::string content( (std::istreambuf_iterator<char>(ifs) ),
(std::istreambuf_iterator<char>() ) );

return 0;
}


I have no clue what's happening after



std:: string content



Every time I have used std::string before has been like



std::string name = "2bdkid";

Converting a dynamic string list of names to a sortable array with Javascript

I have seen several posts on how to convert a string to an array using .split(), but I am curious how I would have a list re-sort it's self everytime a new string is added.


For example, I have an input box where I enter names in the format of 'First Last'. On the button click event, the input div clears, a dynamic list is generated of the names entered, and it reformats them 'Last, First'.


Every time a new name is entered, the list should resort itself alphabetically.


I would have this output div split itself on a delimiter after each name, so that the list is an indexed array of strings, but I don't have a delimiter to split on.


Here is my code so far. I know there are several things I could do to improve this but I'm looking for a very simple answer to storing these values in an array instead of a list of strings just so that they can be sorted alphabetically.


Assume all data will be entered in the format 'First Last' including capitalization.


The comment in all caps involves the 'combine' variable that needs to become an array.





var namesArr = [];//create an empty array that will hold the names

var output = document.getElementById('output');//get the output element (text area).

var name = document.getElementById('name');//get the textbox

function init(){
var nameBtn = document.getElementById('addNameBtn');//get the name button element

var clrBtn = document.getElementById('clearBtn');//get the clear button element

nameBtn.onclick = enterName;//set up your events here

clrBtn.onclick = clearNames;//set up your events here
}

function enterName(){

if(document.getElementById('name').value !==""){

var arr = document.getElementById('name').value.split(" ");
var space = ", ";
var firstname = arr[1];
var lastname = arr[0];
var outputA = [];
var combine = outputA+firstname+space+lastname+"\n";

output.value += combine//I NEED THIS OUTPUT VALUE
//TO BE STORED IN AN ARRAY
//EVERY TIME A NEW STRING IS ENTERED
//SO THAT I CAN USE .sort() on the array.


}
else{
alert("Please enter a name in the format 'First Last'");
}

if(document.getElementById('name').value !==""){

document.getElementById('name').value = "";//clear names input

}

}

function clearNames(){
document.getElementById('name').value = "";//clear names input
document.getElementById('output').value = "";//clear output input
}

init();//this will run when after the DOM loads



Thank you so much for any help or feedback.


qazxsw12345adfhyrdtostring

My toString is awesome



public static String toString() {

return " ";
}

Removing punctuation and capitalizing in C

I'm writing a program for school that asks to read text from a file, capitalizes everything, and removes the punctuation and spaces. The file "Congress.txt" contains



(Congress shall make no law respecting an establishment of religion, or prohibiting the free exercise thereof; or abridging the freedom of speech, or of the press; or the right of the people peaceably to assemble, and to petition the government for a redress of grievances.)


It reads in correctly but what I have so far to remove the punctuation, spaces, and capitalize causes some major problems with junk characters. My code so far is:



void processFile(char line[]) {
FILE *fp;
int i = 0;
char c;

if (!(fp = fopen("congress.txt", "r"))) {
printf("File could not be opened for input.\n");
exit(1);
}

line[i] = '\0';
fseek(fp, 0, SEEK_END);
fseek(fp, 0, SEEK_SET);
for (i = 0; i < MAX; ++i) {
fscanf(fp, "%c", &line[i]);
if (line[i] == ' ')
i++;
else if (ispunct((unsigned char)line[i]))
i++;
else if (islower((unsigned char)line[i])) {
line[i] = toupper((unsigned char)line[i]);
i++;
}
printf("%c", line[i]);
fprintf(csis, "%c", line[i]);
}

fclose(fp);
}


I don't know if it's an issue but I have MAX defined as 272 because that's what the text file is including punctuation and spaces.


My output I am getting is:



C╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠Press any key to continue . . .

How can I add two strings that contain integer to find the sum?

I try to find the sum of two strings without having to convert to integer like using atoi or stoi It is BigInt class implementation


Example of two strings:



BigInt a("-1000");
BigInt b("+999");


I have a class which private members are:



private:
string data;
bool negative;


The purpose of this question is to write a arithmetic operations like +,-,/,*


A way to replace strings in javascript

I am looking for the best way to replace strings in javascript. Only problem, I need it replaced like this:


Here's my string: The brown fox jumps over the brown fence


I need javascript to find two words like this: The **brown** fox jumps over the **brown** fence


And I need to replace the string with what is in the middle of those words: fox jumps over the


I've been looking online but I cant find anything.


Any idea?


Storing The Contents Of A AutoCompleteSource (HistoryList) In a String

All I am simply trying to do is display the AutoCompleteSource.HistoryList in a message box. All the following code does is display the words HistoryList. How can I make it actually show the URLS of the HistoryLIst, in other words I want the contents of the HistoryList to appear in the MessageBox.



string s = AutoCompleteSource.HistoryList;
MessageBox.Show(s, "History", MessageBoxButtons.OK, MessageBoxIcon.Information);

Writing code for Shift Cypher in C#

My class lab has us write a Shift Cypher and Sub Cypher methods that are called in a button click event. Below you will find the code for this problem.


Can someone help me out with the two methods in question and also calling those methods in the event handler?


enter code here



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace String_Stuff
{
public partial class stringForm : Form
{
public stringForm()
{
InitializeComponent();
}

private string SwitchCase(string input)
{
string str1 = input;
string output = str1.ToUpper();

return output;

}


private string Reverse(string input)
{
string str1 = input;
char[] inputArray = input.ToCharArray();
Array.Reverse(inputArray);
string output = new string(inputArray);

return output;
}

private string PigLatin(string input)
{
// rules: words that begin with a consinant-
//is moved to the end and "ay" is added.
// words that begin with a vowel-
// the sylable "ay" is added to the end of the word.
// e.g. eagle -> eagleay, apple->appleay.
string str1 = input;
string ay = "ay";
input = inputTextBox.Text; // already a string, no need to convert
input = input.Substring(1, input.Length - 1) + input.Substring(0, 1);
str1 = " the word in Pig Latin is " + input + ay; // need to use Text property to display string
string output= str1 ;
return output;
}



private string ShiftCypher(string input, int shift)
{
//Each letter in the word is replaced by a letter some fixed number of positions down the alphabet.
//For this lab, shift by 3. Example: program, shifted by 3 will become surjudp

string output = null;
char[] A = null;
A = input.ToCharArray();
int temp;
for (int i = 0; i < input.Length; i++)
{
temp = (int) (A[i] + shift);
output += (char)temp;
}


return output;
}

private string SubCypher(string input, string charsToSub)

{
//Each letter in the word will be replaced by a letter from the corresponding position
//in a substitution alphabet. For this lab use this substitution alphabet: zeroabcdfghijklmnpqstuvwxy.
//Example: disk would become ofqh.
string subAlpha = "zeroabcdfghijklmnpqstuvwxy";
string str1 = input;
string subCypher = subAlpha;



string output = "";
return output;
}



private void transformButton_Click_1(object sender, EventArgs e)
{
string input = inputTextBox.Text;

switchCaseTextBox.Text = SwitchCase(input);
reverseTextBox.Text = Reverse(input);
pigLatinTextBox.Text = PigLatin(input);
shiftTextBox.Text = ShiftCypher(input,shift);
subTextBox.Text = SubCypher(input, charsToSub);
}
}
}

fgets does not prompt for user input. What is the difference?

I have two scenarios using fgets below. Both scenarios are in the same file, as shown below.



struct sth
{
char str[10];
int num;
};

void getIt(struct sth **M){
char *b;
(*M)=malloc(sizeof(struct sth));

printf("give me an integer:");
fgets(b,1,stdin); // output must be an address
(*M)->num = atoi(b);

printf("give me a string:");
fgets((*M)->str,10,stdin);

}


int main(int argc, char const *argv[])
{
struct sth *myThing;
getIt(&myThing);
printf("Heres the string %s\n", myThing->str);
printf("Heres the num \n", myThing->num);
return 0;
}


Here is the output. Notice that it does not prompt the user for the integer, it just prints "give me an integer", and then moves directly on to the next print statement. Why does it do this?



give me an integer:give me a string:sdf
Heres the string sdf

Heres the num


This small problem is a larger problem in a bigger problem, so this is just a microcosm of the larger one.


Split String and Do Calculation in MySQL

Let's say I have given data as string:



+----------+
|Size |
+----------+
|15X10 |
|5X4 |
|3 |
|2X6X5 |
+----------+


I want to write this column as integer like this:



+----------+
|Size |
+----------+
|150 |
|20 |
|3 |
|60 |
+----------+


Some of them are multiply of three numbers, some of them just one number. I can split the string but cannot make MySQL to calculate the number. Thank you.


max no of times a particular character in a string in knuth morris pratt algorithm comes into comparison with the string?

Let



T:String
P:pattern


what is the max no of times a particular character in a string(T) in knuth morris pratt algorithm comes into comparison with the pattern(P) ?


PHP check if string contains maximum 30 letters/numbers in a sequence with preg_match

I'm stuck here and I can't find any results for my question, maybe because english is not my native language.


I want to match lines which contain maximum 30 letters/numbers in a sequence:


Is this even possible with preg_match?



preg_match("/[^A-Za-z0-9](max 30 in a sequence)/", $string)


Strings:



$string = "1234567890123456789012345678901234567890"; // FALSE
$string = "sdfihsgbfsadiousdghiug"; // TRUE
$string = "cfgvsdfsdf786sdf78s9d8g7stdg87stdg78tsd7g0tsd9g7t"; // FALSE
$string = "65656.sdfsdf.sdfsdf"; // TRUE
$string = "ewrwet_t876534875634875687te8---7r9w358wt3587tw3587"; // TRUE
$string = "sd879dtg87dftg87dftg87ftg87tfg087tfgtdf8g7tdf87gt8t___454"; // FALSE

How to put a string into a byte array in x86 assembly?

How do you get a string from stdin and but it in a byte array using sys_read in x86 assembly, NASM? I am having trouble accessing the different indices of the array.


Find the first index of a character in a string

I am supposed to loop through the character of arrays that is passed in and look for the first occurrence of char, then return the index of the first occurrence. if char is not found then I return -1. This seems to work for all characters except the character at 0, which it does not find for some reason.



int find_ch_index(char string[], char ch) {
int i = 0;
while (string[i++]) {
if (string[i] == ch) {
return i;
}
}
return -1;
}

Timepicker Integer Error

I have a timepicker in my preference activity for setting the time when a notification should be displayed. The value is stored as a string, for example: "15:45". To understand the problem, I will further explain what happens next to the value:



SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(context);
String hour = pref.getString("notification_time","");
// notification_time is my preference key
String Hora = hour;
int hours = Integer.parseInt(Hora.substring(0, 2));
int min = Integer.parseInt(Hora.substring(3, 5));
// as you can see, I parse the string, and then use the integers to set the time (see below)
calendar.set(Calendar.HOUR_OF_DAY, hours);
calendar.set(Calendar.MINUTE, min);
calendar.set(Calendar.SECOND, 00);


Now the problem is, My TimePicker stores the value differently, if the time is AM: for example, if you set the time to 07:45, it stores the time in the string as "7:45", not "07:45", and thus this line in the code fails:



int hours = Integer.parseInt(Hora.substring(0, 2));


(Throwing this error, not really necessary to understand the problem):



java.lang.NumberFormatException: Invalid int: "5:"


,because the position for "substring" isnt working anymore. (1 digit stored in the string instead of 2). Same goes for minutes, for example if I set the minutes to 08, my timepicker stores them as 8, and the same problem occurs again.


Now I have thought about two ways to solve this problem: Either I change the code in my settingsactivity and parse the string differently, or I change the way how I store the strings:



if (positiveResult) {
lastHour=picker.getCurrentHour();
lastMinute=picker.getCurrentMinute();
String time=String.valueOf(lastHour)+":"+String.valueOf(lastMinute);

if (callChangeListener(time)) {
persistString(time);
}
setSummary(getSummary());
}


(These are the lines of code responsible for saving the value as a string)


How should I solve the problem?


How can I get Java to check a String for matches to a Pattern starting at the end?

I have a program that is reading lines of input from a file and must extract information from from each line using a regular expression. Each line is the absolute path to a file or folder in a file system that my application creates. Each line has the following format:



/root/folder1/folder2/folder3


What I need to do is separate the String into an array containing the first part of the path and then the last folder as follows:



["/root/folder1/folder2", "folder3"]


My idea of how to do this was to use a regular expression in conjunction with the java.util.regex.Pattern#split(CharSequence, int) method to split the string using the Pattern while limiting the size of the resultant array. However, since this method matches the pattern to the string starting at the beginning, this method won't work for me. I need something with similar functionality that would check the String for matches starting at the end rather that the beginning. Either that or I need a regular expression wizard to help me cook up a new regular expression to accomplish this.


Right now, I'm using the simple regex "[/]" to split the string.


Thanks in advance.


Using pairs of words from a dictionary with no letters in common, find a pair that maximizes the sum of the words' lengths

Question:



Using pairs of words from a dictionary with no letters in common, find a pair that maximizes the sum of the words' lengths


Example Dictionary: mouse, cow, join, key, dog


dog and key share no letters and have a sum of 3+3 = 6


mouse does not work with cow, join, or dog because they all share the letter 'o'


join and key share no letters and have a sum of 4+3 = 7



I had this question in an interview, my solution I came up with is outlined below. I was wondering if there is any way to make it more efficient? I used two BitSets to map the alphabet of two words and AND them together to see if they contain the same letters. I think my algorithm has a complexity is o(n!) which is inefficent, is there a better way to optimize my algorithm?



public static void maximumSum (String[] dictionary) {
// ascii of a = 97
BitSet word1 = new BitSet(26);
BitSet word2 = new BitSet(26);

String maxWord1 = "";
String maxWord2 = "";
int maxSum = -1;

for(int i = 0; i<dictionary.length; i++) {
for(int j = i+1; j<dictionary.length; j++) {
String s1 = dictionary[i];
String s2 = dictionary[j];
for(int k = 0; k<s1.length(); k++) {
word1.set(s1.charAt(k)-97);
}
for(int k = 0; k<s2.length(); k++) {
word2.set(s2.charAt(k)-97);
}
word1.and(word2);
if(word1.cardinality() == 0) {
if(maxSum < s1.length()+s2.length()) {
maxWord1 = s1;
maxWord2 = s2;
maxSum = s1.length()+s2.length();
}
}
word1.clear();
word2.clear();
}
}
if(maxSum == -1)
System.out.println("All the words have letters in common.");
else
System.out.println("'"+maxWord1+"' and '"+maxWord2+"'
have a maximum sum of "+maxSum);
}

public static void main(String[] args) {
String[] dictionary = {"mouse", "cow", "join", "key", "dog"};
maximumSum(dictionary);
}


output:



'join' and 'key' have a maximum sum of 7

Why Wrapper Class does not have pool Similar to Stringpool?

Integer, Character, Double all these are immutable class like String. String has Stringpool to save memory But why they dont have similar pool? I have checked Integer is having a similar pool only upto 127 value but not more than that.


Jquery Numberical Array to String and get a Substr()

I initiated a numerical array inside a javascript and to converted it into a string using join() but when I try to get a substr(), it doesn't to work. There seems to be a techincal error. Please help!



var array = [85, 13, 7, 42, 78, 9];
$("#div1").html("<b>This is the original array:</b><br><br>" + array.join("<br>"));

$("#div2").html("<br><b>This is the converted string:</b><br><br>" + array.join(""));

$("#div3").html("<br><b>The substring (from 0 to 3) is:</b><br><br>" + array.substr(0,3));


NOTE: div1,div2,div3 are 3 seperate divs with ids respectively. Thats where i want to display the results.


is there a way to get rid of spaces after pop_Back() c++?

I used pop back to get rid of a few things on a list now there is blank spaces making so the text things appear further down. is there a way to only use .pop_back(),.empty(), .clear(), .empty(), or .swap()? because i've tried all the ways i can think of just with these.


no code please, just words.


Istream to string conversion with \n characters in C++

how can I convert istream to string, when my istream also includes newline characters and I don't want to escape whitespaces? Thank you.


Different Outputs in Visual Studio and gcc in cygwin

Same code (Simulating a Shift Reduce Parser) gives different outputs in Visual Studio AND gcc (in cygwin). The problem seems to be in the last function where the strings are compared.


(memory leak maybe) After much debugging I found that gcc does not read E+E after accepting it is converted to some weird thing this(must be some ASCII value)->▒▒▒


gcc version: 4.8.3 Visual Studio Ultimate 2013 version: 12.0.30723


Code:



//shift reduce parser
#pragma warning (disable : 4996)
#include<stdio.h>
#include<malloc.h>
#include<string.h>
char stack[10];
int st = -1, n;
char *(*pro), *(*var);
void match(int);
int main()
{
int i;
char s[10];
printf("Enter the number of productions: ");
scanf("%d", &n);
pro = (char**)malloc(sizeof(char*));
var = (char**)malloc(sizeof(char*));
printf("Enter the productions on LEFT and RIGHT sides one at a time:\n");
for (i = 0; i < n; i++)
{
pro[i] = (char*)malloc(sizeof(char));
var[i] = (char*)malloc(sizeof(char));
scanf("%s", var[i]);
printf("->");
scanf("%s", pro[i]);
}
printf("Enter input string: ");
scanf("%s", s);
i = 0;
//Start processing
do
{
stack[++st] = s[i];
printf("%s\n", stack);
match(1);
i++;
} while (s[i] != '\0');


//reduction
i = 1;
while (st >= 0)
{
st--;
i++;
match(i);
printf("%s\n", stack);
}
if (stack[0] == var[0][0])
printf("Accepted");
while (1);
return 0;
}
//matches k characters of stack with productions
void match(int k)
{
int i;

for (i = 0; i < n; i++)
{
if (!(strncmp(&stack[st], pro[i], k)))
{
strncpy(&stack[st], var[i], k);
st -= k - 1; //tentative
i = -1;
if (k == 1)
{
return;
}
}
}
}


Visual Studio Output:



Enter the number of productions: 5
Enter the productions on LEFT and RIGHT sides one at a time:
E
->E+E
E
->E*E
E
->a
E
->b
E
->c
Enter input string: a+b*c
a
E+
E+b
E+E*
E+E*c
E+E*E
E
Accepted


gcc output



Enter the number of productions: 5
Enter the productions on LEFT and RIGHT sides one at a time:
E
->E+E
E
->E*E
E
->a
E
->b
E
->c
Enter input string: a+b*c
a
E+
E+b
E+E*
E+E*c
E+E*E
E+E
E+E


removing the pragma warning has no effect(it is there to use printf and scanf statements in VS)


PS. Iam sort of new here so if you are downvoting this question please specify the reason