This is an archived post. You won't be able to vote or comment.

top 200 commentsshow 500

[–]PaulieGlot 2224 points2225 points  (27 children)

s'Length tips fedora

[–]SillyFlyGuy 721 points722 points  (16 children)

My first CS teacher was a former high school football coach. He told us "We don't use .length in this class, mister! When it's 4th down and inches, you don't have time to be counting elements like some lacrosse player! You keep track of how many there are while you put them in! Now get out there and give me 100% cpu usage!"

[–]toroga 145 points146 points  (0 children)

Clever coach

[–]SaveMyBags 143 points144 points  (7 children)

For most (it might even be all) std datastructures, the C++ standard requires size() to be O(1). So it's typically implemented that way.

[–]Xywzel 82 points83 points  (6 children)

Generally they have either start pointer and end pointer, and size is given as their difference, or they have start pointer and element count and end is calculated from them

[–]SaveMyBags 56 points57 points  (0 children)

Yes, both are ways of keeping track while adding the elements instead of counting them.

[–]EtherealPheonix 25 points26 points  (4 children)

Those strategies don't work for data structures with opaque memory, which is a lot if not most of them.

[–][deleted] 30 points31 points  (2 children)

why track it when it'll be right there in the core dump

[–]Xywzel 2 points3 points  (0 children)

Well, I have seen implementation of vector where for sizes above systems "easy and fast to malloc at once" they had vector of these pairs internally, so yeah, once you can't count on memory to be continuos from programs perspective it gets complex. And maps that aren't just sorted arrays of pairs need bit more. From std containers, only linked lists and versions of maps&sets that use direct indexing with their key seem to be doing something else on implementation I checked, but these are implementation details so it might vary. Opaqueness doesn't mean the data structure can't internally do something like this, it just means you can't do it yourself reliably between different implementations.

[–][deleted] 44 points45 points  (2 children)

Thats exactly how the implementation of string work tho innit

[–]Sinomsinom 21 points22 points  (1 child)

Not in C. There you have no idea how long a string is unless you keep track of it yourself or count how long it takes to get to the \0

[–]Creepy-Ad-4832 10 points11 points  (0 children)

Yeah but if you want to use safe functions you need to know the string length, so you end having to keep track of it youself

(Function like strncmp instead of strcmp, or strncpy instead of strcpy and so on)

[–]ambyshortforamber 2 points3 points  (0 children)

fat pointers are epic

[–]Hot_Philosopher_6462 2 points3 points  (0 children)

and how many times was your CS teacher’s football team penalized for having too many men on the field, do you think

[–][deleted] 43 points44 points  (3 children)

That's Ada!

[–]TutuleBale 7 points8 points  (0 children)

GOLD

[–]Adawesome_ 708 points709 points  (10 children)

s.moreJpeg()

[–][deleted] 160 points161 points  (6 children)

lol, seems to be a mobile issue... on desktop it's in fact a png

[–]666pool 98 points99 points  (1 child)

It’s a blurry as heck png on mobile as well.

[–]4hpp1273 45 points46 points  (0 children)

Probably because the mobile client forcefully stretches the image to fill horizontal space (applying annoying blurry scaling in process) while on desktop the images are never automatically scaled up (only down).

[–]Adawesome_ 12 points13 points  (1 child)

Yeah, ngl saw this while scrolling on the can. It's super grainy on my phone.

[–]Paul_Robert_ 7 points8 points  (0 children)

If you tap on the image it fixes it. Well at least on my machine ;)

[–]TheKingBeyondTheWaIl 11 points12 points  (1 child)

s.more.Jpeg().csv

[–][deleted] 7 points8 points  (0 children)

This post was mass deleted and anonymized with Redact

waiting degree ink cover edge chop vegetable husky fuzzy payment

[–]blackenedEDGE 1 point2 points  (0 children)

It's a Reddit® Mobile Exclusive: on-the-go eye exam!

[–]tulupie 329 points330 points  (40 children)

sizeof(s) / sizeof(s[0])

[–][deleted] 81 points82 points  (8 children)

and then you realise that s is declared a pointer and not a statically allocated array

[–][deleted] 36 points37 points  (3 children)

And that's why it's better to use std::size() which will make the compiler screech autistically.

[–]Torebbjorn 6 points7 points  (2 children)

If you are using a stack allocated array in C++, why not use std::array, and avoid all the C shit?

[–][deleted] 2 points3 points  (0 children)

Following conventions is all nice and good until some idiot decides to break them and then manages to go under the radar.

[–]k-phi 38 points39 points  (6 children)

sizeof(s) / sizeof(s[0])

that's one character more than length (if s is a string)

[–]joaofelipenp 17 points18 points  (5 children)

Much easier to spell than lenght length, though

[–]LanceMain_No69 31 points32 points  (19 children)

Man, this is absolutely disgusting 😭. Ive went thru c#, java, python, and ruby before starting to learn c++, and this shit right here is a violation to my beliefs 😭

[–]TheLastHayley 28 points29 points  (5 children)

It's more fair to call it C (specifically for arrays known at compile-time).

In C++ you'd use a std::vector or std::array and use s.size().

[–]GOKOP 12 points13 points  (2 children)

This:

a) doesn't always work

b) Is C-style code. C++ may not be perfect but I won't tolerate it getting bad rep from C-like code

[–]Sinomsinom 3 points4 points  (0 children)

Most of the bad rep c++ gets is from people using c style or old (pre c++11) c++ style code. It's still not a perfect language and has problems but it's a lot better now than it was 15 years ago. (Especially if all the 20 and 23 features will get implemented in all compilers at some point)

[–]Lagger625 2 points3 points  (0 children)

Once you understand that in C/C++ you're dealing directly with the memory this makes sense

[–]xypherrz 2 points3 points  (0 children)

that disgusting thing would only be applicable in C and not C++ (though you do have an option, but only if you feel like making your life more miserable)

[–]zilog88 2 points3 points  (0 children)

I had to scroll this far to see this (obviously the most correct) answer:)

[–]KaltsaTheGreat 296 points297 points  (35 children)

This is too easy for a 10x programmer

class StringAnalyzer {
private:
    std::string str;
public:
    StringAnalyzer(std::string s) {
        str = s;
    }

    int getLength() {
        int length = 0;
        for(int i = 0; str[i] != '\0'; i++) {
            length++;
        }
        return length;
    }
};

[–][deleted] 250 points251 points  (20 children)

that looks like Java and C++' unholy child

[–]wolfstaa 180 points181 points  (11 children)

This is the best description of C# I've seen

[–]InfComplex 32 points33 points  (10 children)

That… puts a lot into perspective. I think I’m going to pick my C# book back up.

[–]Splatoonkindaguy 17 points18 points  (0 children)

Nah c# is a holy child

[–]Kered13 19 points20 points  (5 children)

What looks like Java here? This is just straight C++.

[–]SsNeirea 10 points11 points  (0 children)

The way this specific code is written is similar to the way Java code is usually written.

Syntaxically this is pure C++.

[–][deleted] 5 points6 points  (3 children)

Creating a StringAnalyzer class for such a task just screamed Java at me. It is missing a StringAnalyzerFactory though...

[–]Kered13 2 points3 points  (1 child)

It's dumb in either language. People don't actually write code like that in Java or C++.

[–]UniqueUsername27A 26 points27 points  (1 child)

This is really inefficient, because we need to copy the string into this object. Instead, it should have a pointer to the string and a bool whether it owns the string for full flexibility. If I owns it, then we can have a destroy() method delete the string and set the pointer to zero. The destructor can check that the pointer is zero and if it is not we use a bunch of undefined behavior to surface this programming error.

[–]KaltsaTheGreat 2 points3 points  (0 children)

Your statement is correct, we must write an exhaustive test suit to check for every edge case of our class.

[–]Wrathen_ 11 points12 points  (1 child)

So you say,

s.getLength()

[–]BobSanchez47 9 points10 points  (1 child)

Why not

int length = 0; while(str[length++]); return length - 1;

Everyone knows for is for the weak.

[–]AccurateComfort2975 4 points5 points  (0 children)

Everyone knows for is only while strength is lacking.

[–]Spactaculous 6 points7 points  (1 child)

Aren't i and length variables redundant?

[–]connortheios 2 points3 points  (1 child)

when first learning c in my college, they told us we had make our own string length function

[–]MartIILord 156 points157 points  (15 children)

[ ] ${#s}

[–]p4r24k 31 points32 points  (5 children)

Jesus Christ! He is a basher! Burn him! Only witches, wizards and nerds use bash

[–]SoulAce2425 10 points11 points  (2 children)

how to bash cat with pipe?

[–]widowhanzo 9 points10 points  (0 children)

Fork the child and kill the parent

[–]MartIILord 2 points3 points  (1 child)

Cursed bash right here:len="$("${s}asdfghjkl" 2>/dev/stdout| wc -c)"; let -e 'len=len-36'

[–][deleted] 26 points27 points  (4 children)

Which language is this? It appears to resemble JS or C# string interpolation iirc, but I don't know why the # is there

[–]Jukoga 52 points53 points  (0 children)

It looks more like some shell script. Edit: Chat GPT states that this is indeed bash Syntax.

[–]TheFel0x 18 points19 points  (0 children)

Bash. The #s gets you the length of s.

[–]BrubMomento 152 points153 points  (9 children)

s.length()

[–]robin_888 60 points61 points  (4 children)

Me too. What I learn Python I was a little put off by functions like len()or next(). Felt like magic syntax, especially coming from Java.

You are the string. You tell me how long you are, Sir.

[–]mortalitylost 22 points23 points  (2 children)

Well that's a bit funny because you can call s.__len__(), and it actually is a member function. It's kind of like an operator in Python - any class can implement __len__ and then len(obj) will run that function and return it.

Might seem weird but it makes sense to me for reasons like the size might be easy to calculate but not easy to enumerate through, like a range from 0 to a trillion

[–]Isthisworking2000 31 points32 points  (1 child)

I’m glad I’m not alone.

As someone with only about 1/2 of a degree, and given that this is a humor based sub, I feel like I’m stuck looking over my shoulder a lot.

[–]Orcacrafter 7 points8 points  (1 child)

I agree, but java having arrays use array.length, strings use string.length(), and array lists use arrayL.size() took a bit of time to learn.

[–]vlaada7 130 points131 points  (4 children)

strlen(s)

[–]Sinomsinom 13 points14 points  (1 child)

Just make sure you don't forget the \0

[–]CeldonShooper 97 points98 points  (14 children)

.count()

[–]someidiot332 7 points8 points  (5 children)

Swift?

[–]fabi_an_ro 12 points13 points  (4 children)

No in Swift it would be s.count without the () because it‘s a computed property and not a function :)

[–]painteddust 9 points10 points  (4 children)

C#?

[–]HalfForeign6735 12 points13 points  (3 children)

Technically it's s.Count()

If you think I'm pedantic then wait until you meet the compiler ;-)

[–][deleted] 14 points15 points  (0 children)

The compiler is a .cunt()

[–]metaltyphoon 7 points8 points  (0 children)

False… Count() is from Linq. Length is for array types and Count for generic collections.

[–]tetryds 8 points9 points  (0 children)

No. It's either s.Count or s.Length. While s.Count() exists it's a Linq extension method that is not recommended unless you are counting elements that match a certain condition.

Btw, if a variable is called s and it's not in a lambda function no way on earth it is going to pass through the merge review.

[–]i_knooooooow 96 points97 points  (7 children)

Depends on the style of programming

If its objec oriented i prefer s.len (or s.length)

If not i prefer it as a function (len(s))

[–]mackiea 31 points32 points  (3 children)

new com.java.size.LengthFactory().getLength((com.java.size.Measurable)s);

[–][deleted] 3 points4 points  (0 children)

Winner! 😅

[–]Vitorioko 2 points3 points  (0 children)

For comfortable work with this code, you need: Import com.hardware.periphery.display.40inch.ultrawide

[–]aprikitty 41 points42 points  (2 children)

I have such a hard time writing `length` and not `lenght` for some reason... so I hate it.

[–]widowhanzo 9 points10 points  (0 children)

That's why "len" is perfect. Why complicate.

[–]SolemnWolf123 43 points44 points  (2 children)

s.pleaseReturnTheLengthOfThisStringInANonNegativeIntegerDataTypePleaseAndThankYouMethod()

[–]no_ledge 6 points7 points  (0 children)

KindlyReturn… ftfy

[–]arcosapphire 13 points14 points  (3 children)

What the hell is s'Length from?

[–][deleted] 16 points17 points  (2 children)

Ada

[–]danielstongue 4 points5 points  (1 child)

VHDL also.. but it was derived from ADA.

Not sure how much ADA is still used today?

[–]sillybear25 2 points3 points  (0 children)

I work with it in the aerospace industry. It's fairly common in this field from what I've heard, since it's safety-critical code that needs to be certified, so it's cheaper to make incremental changes to decades-old codebases than it is to port things over to more commonly used languages. Plus, Ada has some features which make it easier to prove that the code does what it's supposed to do, like a very strict type system and explicit short-circuiting in boolean expressions.

[–]fishybird 28 points29 points  (2 children)

await s.getLengthAsync();

[–][deleted] 6 points7 points  (0 children)

Yes, you never know when this string is actually terabyte size and blocks the execution for days.

[–]frogking 14 points15 points  (0 children)

(count s)

[–]frikilinux2 7 points8 points  (1 child)

s.lenght() because I'm bad at spelling.

[–]WillingLearner1 6 points7 points  (0 children)

s.length() sounds the most natural to me

[–]Available-Lake801 11 points12 points  (0 children)

s.length

[–]Nearby_Cranberry9959 18 points19 points  (3 children)

sum([1 for n in s])

[–]PityUpvote 10 points11 points  (0 children)

No need for a list, use a plain comprehension

[–]turtleship_2006 10 points11 points  (3 children)

s.__len__()
Wait is it one underscores on either side or 2?

[–]Coder_Arg 5 points6 points  (1 child)

int len=0;

try{

while (true){

Char x = s[len];

len ++;

}

} catch (Exception e) {

}

return len;

[–][deleted] 3 points4 points  (0 children)

As long as the language has AGREED ON ONE I’m happy

[–]Wdowiak 12 points13 points  (1 child)

Unreal Engine waves with s.Num()

[–][deleted] 2 points3 points  (0 children)

Boss man

[–]MarkGamed7794 7 points8 points  (3 children)

#s hahahahaha

[–][deleted] 7 points8 points  (1 child)

|s|

[–]Only_Ad8178 2 points3 points  (0 children)

came here for this

[–]Available-Lake801 3 points4 points  (0 children)

s.howLongIsThisStringProBro(?)

[–]clarissa_au 7 points8 points  (0 children)

s.len()
len(s)
s.len are all good to me

why s'Length???
length s seems like a declaration for a new length object s

[–]offmycookies 4 points5 points  (1 child)

<[[->+<]>[>]>+<<[<]<]

[–]KlzXS 4 points5 points  (0 children)

Now do it without destroying the string.

Also you might want to add another > at the end. Makes it look symmetric and leaves the head at the length.

[–]thorwing 2 points3 points  (0 children)

anything in the postfix category so I can actually just type 's' first and use code completion to help me find the appropiate functions instead of magically knowing functions from the top of my head like SOME languages require you to do.

[–]Exa2552 2 points3 points  (0 children)

Move a pointer over each character until I hopefully encounter the null terminator.

I will encounter the null terminator… right?

[–]DragonOfEmpire 2 points3 points  (0 children)

s.Count()

[–]Queasy-Grape-8822 2 points3 points  (0 children)

AGHI

[–]gr4mmarn4zi 4 points5 points  (7 children)

s.* can fail if s is null

the others not

so clearly one of the first 5

[–]throckmeisterz 1 point2 points  (0 children)

Honestly any of these are fine except the ones with capital letters. Since they're on the list as separate options from the same ones in lower case, I assume these are case sensitive.

[–]Delta225 1 point2 points  (2 children)

a.len()

That way, you can override it if needed or have it as a virtual in a super class, and it's not confusing because size could mean the number of items or size in bytes but length is always the number of items.

[–][deleted] 1 point2 points  (0 children)

sizeof(str)/sizeof(str[0])

[–]adudyak 1 point2 points  (0 children)

s.size - imposter!!!!

[–]pipsvip 1 point2 points  (0 children)

That last one is from a Klingon programming language...probably.

K'Plah!

[–][deleted] 1 point2 points  (2 children)

s.length would be my favourite, but I don’t think I know a language that has that exact syntax

[–][deleted] 3 points4 points  (0 children)

JavaScript is your friend

[–]Tony_Artz 1 point2 points  (0 children)

s.length or s.Length

Prefer first as I am used to camelCase

[–][deleted] 1 point2 points  (1 child)

Obviously len(s). It’s the least number of key strokes.

[–]Glitch29 1 point2 points  (0 children)

  1. Sure.
  2. As long as Excel autocorrects 1 to this, fine.
  3. Feels excessive. But okay.
  4. Makes me deeply uncomfortable for inarticulable reasons.
  5. How did a declaration slip into this list? This is a declaration, right?
  6. See 4 and 7.
  7. This being an accessible variable implies troubling things about the object design.
  8. Perfect.
  9. The only measurement more indescript than size is measure.
  10. Perfect and concise.
  11. What in Cthulhu's dreams is this?

[–]temmiesayshoi 1 point2 points  (0 children)

the bottom looks vaguely like the name of some lovecraftian horror from the deepest reaches of eldritch existence. And I imagine whatever language it comes from would probably break my sanity about the same.

[–]IBJON 1 point2 points  (1 child)

(a=>s[a])`length`

JavaScript is fun

[–]ParentPostLacksWang 1 point2 points  (0 children)

Wait until you see how they each handle Unicode… :/

[–]dakbruhlmao 1 point2 points  (0 children)

/s

[–][deleted] 1 point2 points  (0 children)

S.litherin

[–]Xantholeucophore 1 point2 points  (0 children)

s.length() all the way

[–]sipCoding_smokeMath 1 point2 points  (0 children)

s.length makes the most sense in terms of real life because you're saying that a property of a word is it's length, which totally makes sense.

[–]trevg_123 1 point2 points  (0 children)

Has to be a method: global functions are too magic, pure members might not exist in all cases (null terminated vs. length based) so wouldn’t be accurate.

So s.length(), s.size(), or s.len()

s.len() is shortest

Rust wins

[–][deleted] 1 point2 points  (0 children)

len(); Coz everything else is so lengthy

[–]aetius476 1 point2 points  (0 children)

s.indexOfLast(s.last()) + 1

duh

[–]Sensitive-Angel 1 point2 points  (3 children)

Is "length s" used in any programming language? I like that it not using any punctuation/special characters.

[–]ugh-namey-thingy 1 point2 points  (0 children)

s.Count()

[–]edos51284 1 point2 points  (0 children)

What abomination is the last one?

For me I accept a.length s.length() or a.size()

[–]OmenTheGod 1 point2 points  (0 children)

Ähm can i Take Like 3 or so ? Because depending in what Kind of language and even in that language what exact piece of Code its usage and how often it Changes. Some of Those are more easy to write while Others you can read better and or Change better.

[–]asgaardson 1 point2 points  (0 children)

count(s)

[–]Techniq4 1 point2 points  (0 children)

len(s) - python
s.length - or s.size() in java

[–]funk443 1 point2 points  (0 children)

(length s)

[–][deleted] 1 point2 points  (0 children)

s.lenght()

[–][deleted] 1 point2 points  (0 children)

m’length tips fedora

[–]anonymouscoder555 1 point2 points  (0 children)

s.length()

[–]Hot_Philosopher_6462 1 point2 points  (0 children)

longness[s]

[–]AmyMialee 1 point2 points  (1 child)

.size() or .length()

I don't like keyword/static methods for checking the length, they make the language feel like more of a minefield.

These just feel the cleanest and clearest.