Search Results

Search found 44874 results on 1795 pages for 'string format'.

Page 23/1795 | < Previous Page | 19 20 21 22 23 24 25 26 27 28 29 30  | Next Page >

  • Is concatenating with an empty string to do a string conversion really that bad?

    - by polygenelubricants
    Let's say I have two char variables, and later on I want to concatenate them into a string. This is how I would do it: char c1, c2; // ... String s = "" + c1 + c2; I've seen people who say that the "" + "trick" is "ugly", etc, and that you should use String.valueOf or Character.toString instead. I prefer this construct because: I prefer using language feature instead of API call if possible In general, isn't the language usually more stable than the API? If language feature only hides API call, then even stronger reason to prefer it! More abstract! Hiding is good! I like that the c1 and c2 are visually on the same level String.valueOf(c1) + c2 suggests something is special about c1 It's shorter. Is there really a good argument why String.valueOf or Character.toString is preferrable to "" +? Trivia: in java.lang.AssertionError, the following line appears 7 times, each with a different type: this("" + detailMessage);

    Read the article

  • Parsing String into multiple variable length String (C#)

    - by Nassign
    I am currently trying to convert a VB6 program into C#. There was extensive use of string splitting into structure. For example, Dim Sample AS String Sample = "John Doe New York Test Comment" Public Type Struct1 Name As String * 15 Address As String * 10 Comment As String * 20 End Type Dim dataStruct As Struct1 Set dataStruct = Sample When the dataStruct is set, it will automatically split value into the 3 structure member. Is there a special function to do this in C#. The only way I know how to do this is thru Attributes/Annotation describing the length and start position of string. Any other suggestion?

    Read the article

  • Convert Text with newlines to a List<String>

    - by Vaccano
    I need a way to take a list of numbers in string form to a List object. Here is an example: string ids = "10\r\n11\r\n12\r\n13\r\n14\r\n15\r\n16\r\n17\r\n18\r\n19"; List<String> idList = new List<String>(); idList.SomeCoolMethodToParseTheText(ids); <------+ | foreach (string id in idList) | { | // Do stuff with each id. | } | | // This is the Method that I need ----------------+ Is there something in the .net library so that I don't have to write the SomeCoolMethodToParseTheText myself?

    Read the article

  • C#: split a string into runs of characters, numbers and delimited strings and process it

    - by nrkn
    OK my regex is a bit rusty and I've been struggling with this particular problem... I need to split and process a string containing any number of the following, in any order: Chars (lowercase letters only) Quote delimited strings Ints The strings are pretty weird (I don't have control over them). When there's more than one number in a row in the string they're seperated by a comma. They need to be processed in the same order that they appeared in the original string. For example, a string might look like: abc20a"Hi""OK"100,20b With this particular string the resulting call stack would look a bit like: ProcessLetters( new[] { 'a', 'b', 'c' } ); ProcessInts( 20 ); ProcessLetters( 'a' ); ProcessStrings( new[] { "Hi", "OK" } ); ProcessInts( new[] { 100, 20 } ); ProcessLetters( 'b' ); What I could do is treat it a bit like CSV, where you build tokens by processing the characters one at a time, but I think it could be more easily done with a regex?

    Read the article

  • how to dissect string values

    - by nhoyti
    how can i dissect or retrieve string values Here's the sample code that im working on now private void SplitStrings() { List<string> listvalues = new List<string>(); listvalues = (List<string>)Session["mylist"]; string[] strvalues = listvalues.ToArray(); for (int x = 0; x < strvalues.Length; x++) { } } now that i'am able to retrieve List values in my session, how can i separately get the values of each list using foreach or for statement?

    Read the article

  • Write a recursive function in C that converts a number into a string

    - by user3501779
    I'm studying software engineering, and came across this exercise: it asks to write a recursive function in C language that receives a positive integer and an empty string, and "translates" the number into a string. Meaning that after calling the function, the string we sent would contain the number but as a string of its digits. I wrote this function, but when I tried printing the string, it did print the number I sent, but in reverse. This is the function: void strnum(int n, char *str) { if(n) { strnum(n/10, str+1); *str = n%10 + '0'; } } For example, I sent the number 123 on function call, and the output was 321 instead of 123. I also tried exchanging the two lines within the if statement, and it still does the same. I can't figure out what I did wrong. Can someone help please? NOTE: Use of while and for loop statements is not allowed for the exercise.

    Read the article

  • how to generate a random string, and specify the length you want, or better generate unique string on specification you want

    - by HCP
    There is a library to generate Random numbers, so why in't there a library for generation random strings ? In other words how to generate a random string, and specify the length you want, or better generate unique string on specification you want i.e specify the length, a unique string within my application is enough for me. I know I can create a Guid (globally unique identifier) but those are quite long, longer they need to be. int length = 8; string s = RandomString.NextRandomString(length) uniquestringCollection = new UniquestringsCollection(length) string s2 = uniquestringCollection.GetNext();

    Read the article

  • Iterate over the lines of a string

    - by Space_C0wb0y
    I have a multi-line string defined like this: foo = """ this is a multi-line string. """ I need an iterator that iterates over the individual lines of that string. I could of course do it like this: lineiterator = iter(foo.splitlines()) Is there a more direct way of doing this? In this scenario the string has to traversed once for the splitting, and then again by the parser. It doesn't matter in my test-case, since the string is very short there, I am just asking out of curiosity. Python has so many useful and efficient built-ins for such stuff, but I could find nothing that suits this need.

    Read the article

  • Regular expression of unicode characters on string

    - by Marcus King
    I'm working in c# doing some OCR work and have extracted the text I need to work with. Now I need to parse a line using Regular Expressions. string checkNum; string routingNum; string accountNum; Regex regEx = new Regex(@"\u9288\d+\u9288"); Match match = regEx.Match(numbers); if (match.Success) checkNum = match.Value.Remove(0, 1).Remove(match.Value.Length - 1, 1); regEx = new Regex(@"\u9286\d{9}\u9286"); match = regEx.Match(numbers); if(match.Success) routingNum = match.Value.Remove(0, 1).Remove(match.Value.Length - 1, 1); regEx = new Regex(@"\d{10}\u9288"); match = regEx.Match(numbers); if (match.Success) accountNum = match.Value.Remove(match.Value.Length - 1, 1); The problem is that the string contains the necessary unicode characters when I do a .ToCharArray() and inspect the contents of the string, but it never seems to recognize the unicode characters when I parse the string looking for them. I thought strings in C# were unicode by default.

    Read the article

  • Weird problem with string function

    - by wrongusername
    I'm having a weird problem with the following function, which returns a string with all the characters in it after a certain point: string after(int after, string word) { char temp[word.size() - after]; cout << word.size() - after << endl; //output here is as expected for(int a = 0; a < (word.size() - after); a++) { cout << word[a + after]; //and so is this temp[a] = word[a + after]; cout << temp[a]; //and this } cout << endl << temp << endl; //but output here does not always match what I want string returnString = temp; return returnString; } The thing is, when the returned string is 7 chars or less, it works just as expected. When the returned string is 8 chars or more, then it starts spewing nonsense at the end of the expected output. For example, the lines cout << after(1, "12345678") << endl; cout << after(1, "123456789") << endl; gives an output of: 7 22334455667788 2345678 2345678 8 2233445566778899 23456789?,?D~ 23456789?,?D~ What can I do to fix this error, and are there any default C++ functions that can do this for me?

    Read the article

  • Declaring a string array in class header file - compiler thinks string is variable name?

    - by Dave
    Hey everybody, I need a bit of a hand with declaring a string array in my class header file in C++. atm it looks like this: //Maze.h #include <string> class Maze { GLfloat mazeSize, mazeX, mazeY, mazeZ; string* mazeLayout; public: Maze ( ); void render(); }; and the constructor looks like this: //Maze.cpp #include <GL/gl.h> #include "Maze.h" #include <iostream> #include <fstream> Maze::Maze( ) { cin >> mazeSize; mazeLayout = new string[mazeSize]; mazeX = 2/mazeSize; mazeY = 0.25; mazeZ = 2/mazeSize; } I'm getting a compiler error that says: In file included from model-view.cpp:11: Maze.h:14: error: ISO C++ forbids declaration of ‘string’ with no type Maze.h:14: error: expected ‘;’ before ‘*’ token and the only sense that makes to me is that for some reason it thinks I want string as a variable name not as a type declaration. If anybody could help me out that would be fantastic, been looking this up for a while and its giving me the shits lol. Cheers guys

    Read the article

  • how to change ASP.NET Configuration tool connection string

    - by Zviadi
    Hello, how can I change ASP.NET Configuration tool-s connection string name? (Which connection string will ASP.NET Configuration tool will use) I'm learning ASP.NET and everywhere and in book that I'm reading now theres connection string named: LocalSqlServer. I want to use my local sql server database instead of sql express to store Roles, Membership and other data. I have used aspnet_regsql.exe to create needed data structures in my database. after that I changed my web.config to look like: <connectionStrings> <remove name="LocalSqlServer"/> <add name="LocalSqlServer" connectionString="Server=(LOCAL); Database=MyDatabase;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> but when I run ASP.NET Configuration tool it says that: "The connection name 'ApplicationServices' was not found in the applications configuration or the connection string is empty." ASP.NET Configuration tool uses connection string named: ApplicationServices not LocalSqlServer. cause of that I have to modify web.config to: <connectionStrings> <add name="ApplicationServices" connectionString="Server=(LOCAL); Database=MyDatabase;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> and everything works fine. I wish to know why the hell my web site uses connection string named: ApplicationServices and all books and online documentations uses LocalSqlServer? and how to change it to LocalSqlServer? I have: Windows 7 Sql Server 2008 R2 Visual Studio 2010 Premium Project type is website

    Read the article

  • c++ creating ambigram from string

    - by mike_hornbeck
    I have a task to implement "void makeAmbigram(char*)" that will print on screen ambigram of latin string or return something like 'ambigram not possible'. Guess it's just about checking if string contains only of SNOXZHI and printing string backwards. Or am I wrong ? I'm a complete noob when dealing with cpp so that's what I've created : #include <iostream> using namespace std; char[]words; char[]reversed; char[] ret_str(char* s) { if(*s != '\0') ret_str(s+1); return s; } void makeAmbigram(char* c) { /* finding chars XIHNOZS and printing ambigram */ } int main() { cin>>words; reversed = ret_str(words); makeAmbigram(reversed); return 0; } I can reverse string but how to check if my reversed string contains only needed chars ? I've found some function but it's hard or even imposible to implement it for greater amount of chars : http://www.java2s.com/Code/C/String/Findcharacterinstringhowtousestrchr.htm

    Read the article

  • Search and highlight in html with multiple keywords as a single string

    - by Qiusheng
    In JavaScript, by given a html string with tags like: This string has different fonts. <b>This</b> <i>string</i> <span style="background-color: rgb(212, 239, 181);">has</span> <b>different</b> <i>fonts</i>. When user searches for a search term with multiple words like "different fonts". How can I add highlighting to make the html string look like: <b>This</b> <i>string</i> <span style="background-color: rgb(212, 239, 181);">has</span> <span class="highlight"> <b>different</b> <i>fonts</i> </span>. Please note that the search term is treated as a single string as if the words are in a quote, so I cannot search and highlight each word individually.

    Read the article

  • Knockout with ASP.Net MVC2 - HTML Extension Helpers for input controls

    - by Renso
    Goal: Defining Knockout-style input controls can be tedious and also may be something that you may find obtrusive, mixing your HTML with data bind syntax as well as binding your aspx, ascx files to Knockout. The goal is to make specifying Knockout specific HTML tags easy, seamless really, as well as being able to remove references to Knockout easily. Environment considerations: ASP.Net MVC2 or later Knockoutjs.js How to:     public static class HtmlExtensions     {         public static string DataBoundCheckBox(this HtmlHelper helper, string name, bool isChecked, object htmlAttributes)         {             var builder = new TagBuilder("input");             var dic = new RouteValueDictionary(htmlAttributes) { { "data-bind", String.Format("checked: {0}", name) } };             builder.MergeAttributes(dic);             builder.MergeAttribute("type", @"checkbox");             builder.MergeAttribute("name", name);             builder.MergeAttribute("value", @"true");             if (isChecked)             {                 builder.MergeAttribute("checked", @"checked");             }             return builder.ToString(TagRenderMode.SelfClosing);         }         public static MvcHtmlString DataBoundSelectList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList, String optionLabel)         {             var attrProperties = new StringBuilder();             attrProperties.Append(String.Format("optionsText: '{0}'", name));             if (!String.IsNullOrEmpty(optionLabel)) attrProperties.Append(String.Format(", optionsCaption: '{0}'", optionLabel));             attrProperties.Append(String.Format(", value: {0}", name));             var dic = new RouteValueDictionary { { "data-bind", attrProperties.ToString() } };             return helper.DropDownList(name, selectList, optionLabel, dic);         }         public static MvcHtmlString DataBoundSelectList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> selectList, String optionLabel, object htmlAttributes)         {             var attrProperties = new StringBuilder();             attrProperties.Append(String.Format("optionsText: '{0}'", name));             if (!String.IsNullOrEmpty(optionLabel)) attrProperties.Append(String.Format(", optionsCaption: '{0}'", optionLabel));             attrProperties.Append(String.Format(", value: {0}", name));             var dic = new RouteValueDictionary(htmlAttributes) {{"data-bind", attrProperties}};             return helper.DropDownList(name, selectList, optionLabel, dic);         }         public static String DataBoundSelectList(this HtmlHelper helper, String options, String optionsText, String value)         {             return String.Format("<select data-bind=\"options: {0},optionsText: '{1}',value: {2}\"></select>", options, optionsText, value);         }         public static MvcHtmlString DataBoundTextBox(this HtmlHelper helper, string name, object value, object htmlAttributes)         {             var dic = new RouteValueDictionary(htmlAttributes);             dic.Add("data-bind", String.Format("value: {0}", name));             return helper.TextBox(name, value, dic);         }         public static MvcHtmlString DataBoundTextBox(this HtmlHelper helper, string name, string observable, object value, object htmlAttributes)         {             var dic = new RouteValueDictionary(htmlAttributes);             dic.Add("data-bind", String.Format("value: {0}", observable));             return helper.TextBox(name, value, dic);         }         public static MvcHtmlString DataBoundTextArea(this HtmlHelper helper, string name, string value, int rows, int columns, object htmlAttributes)         {             var dic = new RouteValueDictionary(htmlAttributes);             dic.Add("data-bind", String.Format("value: {0}", name));             return helper.TextArea(name, value, rows, columns, dic);         }         public static MvcHtmlString DataBoundTextArea(this HtmlHelper helper, string name, string observable, string value, int rows, int columns, object htmlAttributes)         {             var dic = new RouteValueDictionary(htmlAttributes);             dic.Add("data-bind", String.Format("value: {0}", observable));             return helper.TextArea(name, value, rows, columns, dic);         }         public static string BuildUrlFromExpression<T>(this HtmlHelper helper, Expression<Action<T>> action)         {             var values = CreateRouteValuesFromExpression(action);             var virtualPath = helper.RouteCollection.GetVirtualPath(helper.ViewContext.RequestContext, values);             if (virtualPath != null)             {                 return virtualPath.VirtualPath;             }             return null;         }         public static string ActionLink<T>(this HtmlHelper helper, Expression<Action<T>> action, string linkText)         {             return helper.ActionLink(action, linkText, null);         }         public static string ActionLink<T>(this HtmlHelper helper, Expression<Action<T>> action, string linkText, object htmlAttributes)         {             var values = CreateRouteValuesFromExpression(action);             var controllerName = (string)values["controller"];             var actionName = (string)values["action"];             values.Remove("controller");             values.Remove("action");             return helper.ActionLink(linkText, actionName, controllerName, values, new RouteValueDictionary(htmlAttributes)).ToHtmlString();         }         public static MvcForm Form<T>(this HtmlHelper helper, Expression<Action<T>> action)         {             return helper.Form(action, FormMethod.Post);         }         public static MvcForm Form<T>(this HtmlHelper helper, Expression<Action<T>> action, FormMethod method)         {             var values = CreateRouteValuesFromExpression(action);             string controllerName = (string)values["controller"];             string actionName = (string)values["action"];             values.Remove("controller");             values.Remove("action");             return helper.BeginForm(actionName, controllerName, values, method);         }         public static MvcForm Form<T>(this HtmlHelper helper, Expression<Action<T>> action, FormMethod method, object htmlAttributes)         {             var values = CreateRouteValuesFromExpression(action);             string controllerName = (string)values["controller"];             string actionName = (string)values["action"];             values.Remove("controller");             values.Remove("action");             return helper.BeginForm(actionName, controllerName, values, method, new RouteValueDictionary(htmlAttributes));         }         public static string VertCheckBox(this HtmlHelper helper, string name, bool isChecked)         {             return helper.CustomCheckBox(name, isChecked, null);         }          public static string CustomCheckBox(this HtmlHelper helper, string name, bool isChecked, object htmlAttributes)         {             TagBuilder builder = new TagBuilder("input");             builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));             builder.MergeAttribute("type", "checkbox");             builder.MergeAttribute("name", name);             builder.MergeAttribute("value", "true");             if (isChecked)             {                 builder.MergeAttribute("checked", "checked");             }             return builder.ToString(TagRenderMode.SelfClosing);         }         public static string Script(this HtmlHelper helper, string script, object scriptAttributes)         {             var pathForCRMScripts = ScriptsController.GetPathForCRMScripts();             if (ScriptOptimizerConfig.EnableMinimizedFileLoad)             {                 string newPathForCRM = pathForCRMScripts + "Min/";                 ScriptsController.ServerPathMapper = new ServerPathMapper();                 string fullPath = ScriptsController.ServerMapPath(newPathForCRM);                 if (!File.Exists(fullPath + script))                     return null;                 if (!Directory.Exists(fullPath))                     return null;                 pathForCRMScripts = newPathForCRM;             }             var builder = new TagBuilder("script");             builder.MergeAttributes(new RouteValueDictionary(scriptAttributes));             builder.MergeAttribute("type", @"text/javascript");             builder.MergeAttribute("src", String.Format("{0}{1}", pathForCRMScripts.Replace("~", String.Empty), script));             return builder.ToString(TagRenderMode.SelfClosing);         }         private static RouteValueDictionary CreateRouteValuesFromExpression<T>(Expression<Action<T>> action)         {             if (action == null)                 throw new InvalidOperationException("Action must be provided");             var body = action.Body as MethodCallExpression;             if (body == null)             {                 throw new InvalidOperationException("Expression must be a method call");             }             if (body.Object != action.Parameters[0])             {                 throw new InvalidOperationException("Method call must target lambda argument");             }             // This will build up a RouteValueDictionary containing the controller name, action name, and any             // parameters passed as part of the "action" parameter.             string name = body.Method.Name;             string controllerName = typeof(T).Name;             if (controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))             {                 controllerName = controllerName.Remove(controllerName.Length - 10, 10);             }             var values = BuildParameterValuesFromExpression(body) ?? new RouteValueDictionary();             values.Add("controller", controllerName);             values.Add("action", name);             return values;         }         private static RouteValueDictionary BuildParameterValuesFromExpression(MethodCallExpression call)         {             // Build up a RouteValueDictionary containing parameter names as keys and parameter values             // as values based on the MethodCallExpression passed in.             var values = new RouteValueDictionary();             ParameterInfo[] parameters = call.Method.GetParameters();             // If the passed in method has no parameters, just return an empty dictionary.             if (parameters.Length == 0)             {                 return values;             }             for (int i = 0; i < parameters.Length; i++)             {                 object parameterValue;                 Expression expression = call.Arguments[i];                 // If the current parameter is a constant, just use its value as the parameter value.                 var constant = expression as ConstantExpression;                 if (constant != null)                 {                     parameterValue = constant.Value;                 }                 else                 {                     // Otherwise, compile and execute the expression and use that as the parameter value.                     var function = Expression.Lambda<Func<object>>(Expression.Convert(expression, typeof(object)),                                                                    new ParameterExpression[0]);                     try                     {                         parameterValue = function.Compile()();                     }                     catch                     {                         parameterValue = null;                     }                 }                 values.Add(parameters[i].Name, parameterValue);             }             return values;         }     }   Some observations: The first two DataBoundSelectList overloaded methods are specifically built to load the data right into the drop down box as part of the HTML response stream rather than let Knockout's engine populate the options client-side. The third overloaded method does it client-side via the viewmodel. The first two overloads can be done when you have no requirement to add complex JSON objects to your lists. Furthermore, why render and parse the JSON object when you can have it all built and rendered server-side like any other list control.

    Read the article

  • Parse int to string with stringstream

    - by SoulBeaver
    Well! I feel really stupid for this question, and I wholly don't mind if I get downvoted for this, but I guess I wouldn't be posting this if I had not at least made an earnest attempt at looking for the solution. I'm currently working on Euler Problem 4, finding the largest palindromic number of two three-digit numbers [100..999]. As you might guess, I'm at the part where I have to work with the integer I made. I looked up a few sites and saw a few standards for converting an Int to a String, one of which included stringstream. So my code looked like this: // tempTotal is my int value I want converted. void toString( int tempTotal, string &str ) { ostringstream ss; // C++ Standard compliant method. ss << tempTotal; str = ss.str(); // Overwrite referenced value of given string. } and the function calling it was: else { toString( tempTotal, store ); cout << loop1 << " x " << loop2 << "= " << store << endl; } So far, so good. I can't really see an error in what I've written, but the output gives me the address to something. It stays constant, so I don't really know what the program is doing there. Secondly, I tried .ToString(), string.valueOf( tempTotal ), (string)tempTotal, or simply store = temptotal. All refused to work. When I simply tried doing an implicit cast with store = tempTotal, it didn't give me a value at all. When I tried checking output it literally printed nothing. I don't know if anything was copied into my string that simply isn't a printable character, or if the compiler just ignored it. I really don't know. So even though I feel this is a really, really lame question, I just have to ask: How do I convert that stupid integer to a string with the stringstream? The other tries are more or less irrelevant for me, I just really want to know why my stringstream solution isn't working.

    Read the article

  • Increasing understanding of validating a string with PHP string functions

    - by user1554264
    I've just started attempts to validate data in PHP and I'm trying to understand this concept better. I was expecting the string passed as an argument to the $data parameter for the test_input() function to be formatted by the following PHP functions. trim() to remove white space from the end of the string stripslashes() to return a string with backslashes stripped off htmlspecialchars() to convert special characters to HTML entities The issue is that the string that I am echoing at the end of the function is not being formatted in the way I desire at all. In fact it looks exactly the same when I run this code on my server - no white space removed, the backslash is not stripped and no special characters converted to HTML entities. My question is have I gone about this in the wrong approach? Should I be creating the variable called $santised_input on 3 separate lines with each of the functions trim(), stripslashes() and htmlspecialchars()? By my understanding surely I am overwriting the value of the $santised_input variable each time I recreate it on a new line of code. Therefore the trim() and stripslashes() string functions will never be executed. What I am trying to achieve is using the "$santised_input" variable to run all of these PHP string functions when the $data argument is passed to my test_input() function. In other words can these string functions be chained together so that I only need to create $santised_input once? <?php function test_input($data) { $santised_input = trim($data); $santised_input = stripslashes($data); $santised_input = htmlspecialchars($data); echo $santised_input; } test_input("%22%3E%3Cscript%3Ealert('hacked')%3C/script%3E\ "); //Does not output desired result "&quot;&gt;&lt;script&gt;alert('hacked')&lt;/script&gt;" ?>

    Read the article

  • Probelm with String.split() in java

    - by Matt
    What I am trying to do is read a .java file, and pick out all of the identifiers and store them in a list. My problem is with the .split() method. If you run this code the way it is, you will get ArrayOutOfBounds, but if you change the delimiter from "." to anything else, the code works. But I need to lines parsed by "." so is there another way I could accomplish this? import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.*; public class MyHash { private static String[] reserved = new String[100]; private static List list = new LinkedList(); private static List list2 = new LinkedList(); public static void main (String args[]){ Hashtable hashtable = new Hashtable(997); makeReserved(); readFile(); String line; ListIterator itr = list.listIterator(); int listIndex = 0; while (listIndex < list.size()) { if (itr.hasNext()){ line = itr.next().toString(); //PROBLEM IS HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! String[] words = line.split("."); //CHANGE THIS AND IT WILL WORK System.out.println(words[0]); //TESTING TO SEE IF IT WORKED } listIndex++; } } public static void readFile() { String text; String[] words; BufferedReader in = null; try { in = new BufferedReader(new FileReader("MyHash.java")); //NAME OF INPUT FILE } catch (FileNotFoundException ex) { Logger.getLogger(MyHash.class.getName()).log(Level.SEVERE, null, ex); } try { while ((text = in.readLine()) != null){ text = text.trim(); words = text.split("\\s+"); for (int i = 0; i < words.length; i++){ list.add(words[i]); } for (int j = 0; j < reserved.length; j++){ if (list.contains(reserved[j])){ list.remove(reserved[j]); } } } } catch (IOException ex) { Logger.getLogger(MyHash.class.getName()).log(Level.SEVERE, null, ex); } try { in.close(); } catch (IOException ex) { Logger.getLogger(MyHash.class.getName()).log(Level.SEVERE, null, ex); } } public static int keyIt (int x) { int key = x % 997; return key; } public static int horner (String word){ int length = word.length(); char[] letters = new char[length]; for (int i = 0; i < length; i++){ letters[i]=word.charAt(i); } char[] alphabet = new char[26]; String abc = "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < 26; i++){ alphabet[i]=abc.charAt(i); } int[] numbers = new int[length]; int place = 0; for (int i = 0; i < length; i++){ for (int j = 0; j < 26; j++){ if (alphabet[j]==letters[i]){ numbers[place]=j+1; place++; } } } int hornered = numbers[0] * 32; for (int i = 1; i < numbers.length; i++){ hornered += numbers[i]; if (i == numbers.length -1){ return hornered; } hornered = hornered % 997; hornered *= 32; } return hornered; } public static String[] makeReserved (){ reserved[0] = "abstract"; reserved[1] = "assert"; reserved[2] = "boolean"; reserved[3] = "break"; reserved[4] = "byte"; reserved[5] = "case"; reserved[6] = "catch"; reserved[7] = "char"; reserved[8] = "class"; reserved[9] = "const"; reserved[10] = "continue"; reserved[11] = "default"; reserved[12] = "do"; reserved[13] = "double"; reserved[14] = "else"; reserved[15] = "enum"; reserved[16] = "extends"; reserved[17] = "false"; reserved[18] = "final"; reserved[19] = "finally"; reserved[20] = "float"; reserved[21] = "for"; reserved[22] = "goto"; reserved[23] = "if"; reserved[24] = "implements"; reserved[25] = "import"; reserved[26] = "instanceof"; reserved[27] = "int"; reserved[28] = "interface"; reserved[29] = "long"; reserved[30] = "native"; reserved[31] = "new"; reserved[32] = "null"; reserved[33] = "package"; reserved[34] = "private"; reserved[35] = "protected"; reserved[36] = "public"; reserved[37] = "return"; reserved[38] = "short"; reserved[39] = "static"; reserved[40] = "strictfp"; reserved[41] = "super"; reserved[42] = "switch"; reserved[43] = "synchronize"; reserved[44] = "this"; reserved[45] = "throw"; reserved[46] = "throws"; reserved[47] = "trasient"; reserved[48] = "true"; reserved[49] = "try"; reserved[50] = "void"; reserved[51] = "volatile"; reserved[52] = "while"; reserved[53] = "="; reserved[54] = "=="; reserved[55] = "!="; reserved[56] = "+"; reserved[57] = "-"; reserved[58] = "*"; reserved[59] = "/"; reserved[60] = "{"; reserved[61] = "}"; return reserved; } }

    Read the article

  • how to split a string by another string ?

    - by Nikhil Vaghela
    I have a string in following format "TestString 1 <^ TestString 2 <^ Test String3 Which i want to split by "<^" string. Using following statement it gives the output i want "TestString 1 <^> TestString 2 <^> Test String3" .Split("<^>".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) But if my string contains "<" , "" or "^" anywhere in the text then above split statement will consider that as well Any idea how to split only for "<^" string ?

    Read the article

  • How Do I Parse a String?

    - by Russ
    I am new to bash, and I am creating a script that loops through the files in a directory and based on part of the filename, does something with the file, so far I have this: #!/bin/bash DIR="/Users/me/Documents/import/*" for f in "$DIR" do $t=?????? echo "Loading $f int $t..." done so $f will output something like this: /Users/me/Documents/import/time_dim-1272037430173 out of this, I want time_dim, the directory can be variable length and -1272037430173 is a fixed length (it's the unix timestamp btw). What is the best way to go about this?

    Read the article

< Previous Page | 19 20 21 22 23 24 25 26 27 28 29 30  | Next Page >