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 .