分割并大写


14

挑战:

给定字符串在特定位置处分开,并大写给定单词的第一个字符。当且仅当第一个单词的大写字母已经被大写时,才将其大写

输入:

字符串s和字符c

每次出现的字符串都c被替换为首个大写的char

例子 :

STRING(s)             CHARACTER(c)  RESULT
Hello_world           _             HelloWorld
me,no,like            ,             meNoLike
you-got-it            -             youGotIt
Am^I^clear            ^             AmIClear
go!full!caps          !             goFullCaps
weird&but&tRue        &             weirdButTRue
ProbleM1fixed1no      1             ProbleMFixedNo
!prob!!lem!s!Olved!!  !             ProbLemSOlved

注意 :

  • 给定的输入将始终有效。ie:第一个将始终是一个字符串,至少包含一个要替换的字符实例。第二个将始终是单个字符。
  • 输入字符串的长度将大于4。
  • 至少有一次出现该字符的情况。

  • 确保输入仅包含字母和分隔符(感谢@Arnauld)

  • 分隔符是不是字母(az / AZ)的任何东西(@Dennis建议)

获奖标准:

这是因此每种语言的最短代码(以字节为单位)获胜。


  1. 感谢@JonathanAllan指出了两个错误。

7
创建测试用例的技巧:使每一个至少覆盖一个角壳。您所有的测试用例基本上都是相同的(也许有的除外1)。尝试考虑解决方案可能如何失败,并为这种情况做一个测试案例。例如:字母作为分隔符,分隔符是最后一个字符,连续的分隔符,依此类推。不需要有很多不会测试不同事物的测试用例。
Stewie Griffin

您在最后一个测试用例中缺少分隔符-应该有一个!那里。我自己编辑它,但是没有足够的字符来做。
奥利安

1
由于对规范进行了多次更改,因此我对此表示反对。在阿里纳斯,你需要提很多比去年测试用例越早,该字符串可能包含2个或以上连续的“分隔符”,而我们不能保证信将始终遵循“分隔符”。
毛茸茸的

2
我查了一下:Stewie没有建议任何测试用例,但是他问第一个或最后一个字符可以是分隔符,以及是否可以有连续的分隔符。将来,请考虑使用沙盒将所有这些详细信息整理出来,然后再上线。由于规范的更改而使您的答案无效是令人沮丧的。最令人惊讶的是,即使程序不需要字符,也必须将字符作为输入。那根本没有道理。
丹尼斯

1
我们可以有一个带有分隔符的测试用例吗.,我可以想象一些字符串拆分函数在与之苦苦挣扎。
JAD

Answers:




5

JavaScript(ES6),58 56字节

@ l4m2 / @Downgoat节省了2个字节

以currying语法接受输入(s)(c)

s=>c=>s.replace(u=/./g,x=>u=x==c?'':u?x:x.toUpperCase())

在线尝试!

已评论

s => c =>                  // given s and c
  s.replace(u = /./g, x => // initialize u to a RegExp; replace each character x in s with,
    u =                    // and update u to:
      x == c ?             //   if x is the separator:
        ''                 //     an empty string
      :                    //   else:
        u ?                //     if u is not an empty string:
          x                //       x unchanged
        :                  //     else:
          x.toUpperCase()  //       x capitalized
  )                        // end of replace()

安慰56个字节s=>c=>s.replace(RegExp(c+".","g"),m=>m[1].toUpperCase()),因为它不适用于特殊的正则表达式字符
Conor O'Brien

50个字节。如果您不打扰第二个输入,则为47,这无关紧要。
毛茸茸的

1
@粗野的谢谢!由于新规则与原始规则大不相同,因此我将其添加为单独的版本。
阿诺尔德

1
失败!prob!!lem!s!Olved!!
l4m2 '18年

@ l4m2,这是一个新的测试用例,它再次更改了规范。一个+.的正则表达式会得到解决的。
毛茸茸的



3

果冻,8字节

Œt⁸1¦«⁸ḟ

在线尝试!

怎么运行的

Œt⁸1¦«⁸ḟ  Main link. Left argument: s (string). Right argument: c (character).

Œt        Title case; capitalize the first character of each word.
  ⁸1¦     Replace the first character of the result with the first character of s.
     «⁸   Take the character-wise minimum of the result and s.
          Note that uppercase letters have lower code points than lowercase ones.
       ḟ  Filterfalse; remove all occurrences of c.

3

八度8366,64个字节

感谢Luis Mendo,节省了2个字节。upper代替toupper

@(s,c,k=upper(s(i=find(s==c)+1)))[strsplit({s(i)=k,s}{2},c){:}];

在线尝试!

哇,这可能是我写过的最混乱的八度代码了!这将使用两个招数张贴在提示问题中技巧,即参数列表和单元格数组。

说明:

参数列表输入:

@(s,c,k        % An anonymous function that may take three input variables, s, c, k
               % where the third argument has the default value:
 k=upper(s(i=find(s==c)+1))

ks每个分隔符之后的第一个字符c,转换为大写。每个大写字符的索引存储在中i

单元阵列主体:

我们创建了一个包含两个元素的单元格数组,一个是我们说所有第i个字符都应替换为中的第i个字符k,另一个是使用s,现在已经更新了。我们使用索引该索引,{2}以便仅返回整个修改后的字符串。strsplit将其馈入,将其在分隔符处拆分为单元格。我们使用将其转换为逗号分隔的列表{:},并使用方括号将其连接回字符串[]

道歉,如果这对您没有任何意义...对我来说几乎没有道理:P


3

视网膜0.8.2,20字节

T`lLp`LL_`[\W\d_]+.?

在线尝试!仅采用字符串,分隔符为可选。删除所有非字母字符,但随后的任何字母字符均大写。先前的34字节版本接受任意输入:

T`l`L`(?=.*(.)$)\1+.
(?=.*(.)$)\1

在线尝试!链接包括测试套件。假设输入由串联在一起的字符串和字符组成。说明:第一级在出现结束字符后立即将所有字符从小写转换为大写,然后第二阶段删除所有出现的结束字符。

对于这两种解决方案,也可以使用从右到左的匹配代替+


由于保证输入仅包含字母字符和分隔符,因此您可以使用[^a-z]而不是先行符在线尝试!
Kritixi Lithos


2

Röda57 54字节

牛嘎嘎声 -3个字节

{(_/`\Q$_`)|{pull;[upperCase(_[:1]),_1[1:]]if[#_1>0]}}

在线尝试!

说明:

{
  (_/`\Q$_`)| /* Pull two strings and split the first with the second */
  {
    pull;                /* Pull one string and print it */
                         /* For each string _1 in the stream: */
                         /*   If _1 is not empty: */
    [                    /*     Print: */
      upperCase(_[:1]),  /*       The first character capitalized */
      _1[1:]             /*       The rest of characters */
    ]if[#_1>0]           /*   End if */
  }
}

你可以离开了\E,从正则表达式,以及_[0:1]_[:1]
Kritixi LITHOS

2

V,6 7字节

不使用参数保存1个字节

ÓÁˆ/õ±

在线尝试!

该程序将文本作为输入,并将char作为参数。

十六进制转储:

00000000: d3c1 882f f5b1                           .../..

这是一个简单的替代。未压缩,如下所示

:s/\A(.)/\u\1/g

执行全局替换,其中用大写的第一个捕获组替换\A一个非字母字符,后跟一个字符(.)\u\1


输入的地方不工作c是一个特殊的正则表达式字符
康纳尔奥布莱恩

1
@ ConorO'Brien修复,由于这个原因,我找到了一个更短的解决方法:D
Kritixi Lithos

2

Scala,83个字节

def f(s:String)={val w=s.split("[^a-zA-Z]");w(0)+w.tail.map(_.capitalize).mkString}

在线尝试!

说明:

def f(s: String) = {                        // takes a String "s" as input
  val w = s.split("[^a-zA-Z]");             // split on non-alpha chars
  w(0) + w.tail.map(_.capitalize).mkString  // upper case first letter of all words except first one and join array into a String
}                                           //


1

05AB1E,9个字节

¡ćsvyćusJ

在线尝试!

说明

¡           # split the string on the char
 ć          # extract the head of the resulting list
  s         # swap the head to the bottom of the stack
   vy       # for each string y in the rest of the list
     ću     # extract the head and capitalize it
       s    # swap it below the rest of the string
        J   # join everything to one string

1

PHP,91 83字节

$a=explode($argv[2],$argv[1]);echo array_shift($a);foreach($a as$i)echo ucfirst($i);

用运行-r。使用split而不是explode缩短了2个字节,但是^测试由于正则表达式而失败。

-8感谢Med


1
您可以从for循环中删除{and },它将仅将下一条语句视为条件主体。
Med

1
您甚至可以在循环内进行回显:$a=explode($argv[2],$argv[1]);echo array_shift($a);foreach($a as$i)echo ucfirst($i);
Med

0

Groovy,43个字节,45个字节

s.replaceAll(/\$c(.)/){it[1].toUpperCase()}

在线尝试。测试套件包括排除最后一个项目,因为它缺少分隔符char c


0

Go,138 92 87字节

由于@Dennis的标题大小写的想法,丢弃了46个字节。

func f(s,d string){p:=Split(s,d);Print(p[0]+Replace(Title(Join(p[1:]," "))," ","",-1))}

在线尝试!


0

外壳,10字节

ΣΓ·:mΓo:ax

在线尝试!

说明

ΣΓ·:mΓ(:a)x  -- example inputs: 'x' "abxbcxcdxdex"
          x  -- split on character: ["ab","bc","cd","de"]
 Γ           -- pattern match (x = head) (xs = tail) and do..
  ·:         -- | construct list (x:xs) but with the second argument do..
    m        -- | | map (eg. "bc")
     Γ(  )   -- | | | pattern match on first character
      ( a)   -- | | | | upper-case it
      (: )   -- | | | | and join again
             -- | | | : "Bc"
             -- | | : ["Bc","Cd","De"]
             -- : ["ab","Bc","Cd","De"]
Σ            -- concatenate: "abBcCdDe"


0

Java 10,141个字节

s->c->{var r=s.split("\\"+c);var r=a[0],t;for(int i=0;++i<a.length;r+=t.isEmpty()?"":(char)(t.charAt(0)&~32)+t.substring(1))t=a[i];return r;}

在线尝试。

说明:

s->c->{                    // Method with String and character parameters and String return-type
  var r=s.split("\\"+c);   //  Split String by character (with potential regex char)
  var r=a[0],              //  Result-String, starting at the first item
      t;                   //  Temp-String to reduce bytes
  for(int i=0;++i<a.length;//  Loop in the range [1, length_of_array)
      r+=                  //    After every iteration: append the result-String with:
         t.isEmpty()?      //     If the current item empty:
          ""               //      Append nothing
         :                 //     Else:
          (char)(t.charAt(0)&~32)
                           //      Capitalize the first character
          +t.substring(1)) //     And append the other characters as is
    t=a[i];                //   Set `t` to the current String-item of the array
  return r;}               //  Return the result-String

0

R,87字节

g<-function(s,x,z=strsplit(s,x,T)[[1]])cat(z[1],capwords(z[-1]),sep="")
example(chartr)

在线尝试!

使用此技巧无法在TIO中正确执行,因此我对其进行了模拟。

我们需要T否则测试案例之一将失败。


0

Stax,11 个字节

óKo{cplòüö\

运行并调试

说明

/BsF1:/s^s|dl                 # Full Program, unpacked, Implicit Input
/                             # Split on substrings (Split input with symbol to split on)
 B                            # Remove first element from array. Push the tail of the array, then the removed element.
  s                           # Swap first two elements of stack
   F                          # Start for loop
    1:/                       # Split array at index; push both parts.
       s^s                    # Swap first two elements of stack, capitalize character, swap first two elements 
         |dl                  # Get length of stack, listify that amount (entire stack), implicit output of array

我确实想以某些方式修复某些部分。我可以将其压缩到大约8个字节,但是在最后一个测试用例>。<上失败了。


0

红宝石 -pl,36个字节

$_.gsub!(/[^a-z]+(.|$)/i){$1.upcase}

在线尝试!

仅接受不带第二个参数的字符串。使用gsub!方法的块版本,因为使用通用gsub! x,y语法$1不容易用匹配数据填充。|$对于最后带有分隔符的测试用例,在regex中是必需的。


0

Python 3,77个字节

o=[]
for x in s.split(c): o.append(chr(ord(x[0])-32)+x[1:])
print(''.join(o))

在线尝试!

这假定字符串是ASCII编码的,并且假定sc是包含输入的预加载变量。

for x in s.split(x)       #loop through items in the string s split by x
    o.append(             #add the following to c
        chr(              #turn the following number into a character
            ord(          #turn the following character into a number
                x[0]      #the first character in string x
            )-32          #subtract 32 from this number
        +x[1:]            #add everything past and including the second character in string x

此解决方案基于以下事实:在ASCII编码中,小写字母位于大写字母之后的32个条目中

编辑:我只是意识到这也将字符串中的第一个字符大写,这是不应该的。但我为我的废话感到骄傲,所以如果允许的话,我会放弃


什么是s应该是什么?
穆罕默德·萨尔曼

@MuhammadSalmanA string s and a character c.
戴文·

可爱的,使它工作,请转到此处,看看它是否有效:TIO。什么时候能告诉我?
穆罕默德·萨尔曼

哎呀!我刚刚意识到我在更改变量名称时犯了一个错误,c = []应该是任何其他变量
Davin Miler

@MuhammadSalman 在这里
Davin Miler
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.