Skip to main content

Posts

Showing posts with the label string

JavaScript Repeat a String

 题目要求: Repeat a given string str (first argument) for num times (second argument). Return an empty string if num is not a positive number. For the purpose of this challenge, do not use the built-in .repeat() method. 将给定的字符串 str (第一个参数)重复 num 次(第二个参数)。 如果 num 不是正数,则返回一个空字符串。 出于本次挑战的目的,请勿使用内置的 .repeat() 方法。不允许使用内置的.repeat。 原来思路是用string*num,结果发现JavaScript没有字符串的乘法方法。可以用for循环。 function   repeatStringNumTimes ( str ,  num ) {    var   temString  = "" ;    if  ( num <= 0 )   {      temString  =  "" ;   }    else   {      for ( let   i = 0 ; i < num ; i ++)     {        temString += str ;     }   }    return   temString ; } console . log ( repeatStringNumTimes ( "abc" ,  3 )); repeatStringNumTimes ( "abc" ,  3 );

javascript Find the Longest Word in a String

  Return the length of the longest word in the provided sentence. Your response should be a number. 思路:先把句子转化为单词数组,然后创建一个变量,并赋初值为0,让这个变量与每个单词的长度进行比较,如果这个变量小于等于这个单词长度,则将这个变量更新为单词的长度。在一个for循环中比较下去,就可以得到最长的单词的长度。 function   findLongestWordLength ( str ) {    var   strarr  =  str . split ( " " ); //用空格进行分割.    var   longest  =  0 ; //记录并更新每两个比较    console . log ( strarr );    for ( let   i = 0 ; i < strarr . length ; i ++){      if  ( longest <= strarr [ i ]. length )     {        longest  =  strarr [ i ]. length ;     }   }    console . log ( longest );    return   longest ; } findLongestWordLength ( "The quick brown fox jumped over the lazy dog" );

python3 string find method

Description It determines if string str occurs in string, or in a substring of string if starting index beg and ending index end are given. Syntax str.find(str, beg=0, end=len(string)) Parameters str − This specifies the string to be searched. beg − This is the starting index, by default its 0. end − This is the ending index, by default its equal to the length of the string. Return Value Index if found and -1 otherwise. Example: Python 3.6.6 (v3.6.6:4cf1f54eb7, Jun 27 2018, 03:37:03) [MSC v.1900 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> str1 = "This is a string to test the find method." >>> str2 = "string" >>> print(str1.find(str2)) 10 >>> print(str1.find(str2,10)) 10 >>> print(str1.find(str2,10+1)) -1 >>>